Python字符串函数使用详解

2021-12-19 22:21
Python的友好在于提供了非常好强大的功能函数模块,对于字符串的使用,同样提供许多简单便捷的字符串函数。Python 字符串自带了很多有用的函数,在字符串函数之前先介绍一个非常实用的dir()内置函数,因为对每一个初学者还是大佬级别的python程序员,都不能完全记住所有方法。而该函数可以查看所有这些函数,可调用 dir 并将参数指定为任何字符串(如 dir("")),其返回值包括字符串可以使用的变量、方法和定义的类型。
  1. >> dir("")
  2. ['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
  3. '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
  4. '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count',
  5. 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric',
  6. 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition',
  7. 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
1. 函数 index 和 find 之间的差别在于没有找到指定子串时的情形 ,示例如下:

函数index会抛出异常 ValueError,而如果没有找到指定的子串,函数find将返回 -1。
2.字符串搜索函数通常从左往右(从开头往末尾)搜索,但以 r 打头的函数从右往左搜索。例如:
分享到:
文章评论 · 所有评论
评论请遵守当地法律法规
点击加载更多
本月点击排行
精彩图片
京ICP备14056871号
Copyright ©2022 USN, All Rights Reserved