Python--字符串整理

 函数,
# ['__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',
# 'isascii', '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']


s1 = 'nihao'

for i in range(len(s1)):
print(s1[i])

for i in s1:
print(i)
i=0
while i<=len(s1)-1:
print(s1[i])
i+=1

s3 = 'ni','hao','ma'
for i in s3:
print(i)

切片 nihao s1[1:2] 从哪开始到哪结束 i
nihaomahenhao s1[1:2:3] 步长-1可以反转

s2='nihao'
print(s2[1:2])

s3='nihaomahenhao'
print(s3[::2])

s4 = 'niahomawohenhao'
print(s4.count('a')) #找出a在s4里面的位置 count('n'1,5) count('a',5)

print(s4.startswith('ah')) # 判断字符错中 是否有这一串字符 判断已什么开头
print(s4.strip()) #删除 string 字符串末尾的空格


str1 = "Line1-abcdef Line2-abc Line4-abcd";
print(str1.split( )) # 以空格为分隔符,包含 str -- 分隔符,默认为所有的空字符,包括空格、换行( )、制表符( )等。
print(str1.split(' ', 1 ))# 以空格为分隔符,分隔成两个 num -- 分割次数。默认为 -1, 即分隔所有。


str.replace(old, new[, max])
old -- 将被替换的子字符串。
new -- 新字符串,用于替换old子字符串。
max -- 可选字符串, 替换不超过 max 次

str = "this is string example....wow!!! this is really string";
print( str.replace("is", "was"));
print( str.replace("is", "was", 3));

isalnum() 字符错由字母或数字组成
isalpha() 字符串只由字母组成
isdecimal() 检查字符串是否只包含十进制字符

ss1 = 'nihaoma'
print(ss1.find('a')) #反会a在字符串中的位置 不存在返回-1
print(ss1.find('a',3)) #从下标三开始,包括下标三
print(ss1.find('a',3,4)) #从下表三开始,查到下表4


ss2 = 'ni,hao'
re = ss2.capitalize() #首字母大写
re = ss2.swapcase() #大小写互换
re = ss2.title() #以逗号分隔,首字母大写 .
print(re)

ss3 = 'ni,hao'
re = ss3.center(55)
print(re)
原文地址:https://www.cnblogs.com/Rice-Ayba/p/13267419.html