Python3字符串-最容易理解的方式

字符串的创建

字符串创建符号
' '
" "
''' '''
""" """

转义符

>>> string_long = """This is another long string
... value that will span multiple
... lines in the output"""
>>> print(string_long)
This is another long string
value that will span multiple
lines in the output
>>> string_long
'This is another long string
value that will span multiple
lines in the output'

字符串索引

字符串:bright Hello!

bright Hello!
0 1 2 3 4 5 6 7 8 9 10 11 12


案例

字符串操作

>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

字符串去空格

通过strip(),lstrip(),rstrip()方法去除字符串的空格

S.strip()去掉字符串的左右空格
S.lstrip()去掉字符串的左边空格
S.rstrip()去掉字符串的右边空格

字符串大小写

通过下面的upper(),lower()等方法来转换大小写

S.upper()#S中的字母大写
S.lower() #S中的字母小写
S.capitalize() #首字母大写
S.istitle() #S是否是首字母大写的
S.isupper() #S中的字母是否全是大写
S.islower() #S中的字母是否全是小写

字符串其他方法

字符串相关的其他方法:count() join()方法等

S.center(width, [fillchar]) #中间对齐
S.count(substr, [start, [end]]) #计算substr在S中出现的次数
S.expandtabs([tabsize]) #把S中的tab字符替换没空格,每个tab替换为tabsize个空格,默认是8个
S.isalnum() #是否全是字母和数字,并至少有一个字符
S.isalpha() #是否全是字母,并至少有一个字符
S.isspace() #是否全是空白字符,并至少有一个字符
S.join()#S中的join,把列表生成一个字符串对象
S.ljust(width,[fillchar]) #输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。
S.rjust(width,[fillchar]) #右对齐
S.splitlines([keepends]) #把S按照行分割符分为一个list,keepends是一个bool值,如果为真每行后而会保留行分割符。
S.swapcase() #大小写互换

字符串相加
我们通过操作符号+来进行字符串的相加,不过建议还是用其他的方式来进行字符串的拼接,这样效率高点。
原因:在循环连接字符串的时候,他每次连接一次,就要重新开辟空间,然后把字符串连接起来,再放入新的空间,再一次循环,又要开辟新的空间,把字符串连接起来放入新的空间,如此反复,内存操作比较频繁,每次都要计算内存空间,然后开辟内存空间,再释放内存空间,效率非常低。

字符串编码

格式化字符串

原文地址:https://www.cnblogs.com/brightyuxl/p/9874172.html