python 字符串方法
capitalize (把首字母转换成大写)
count (统计指定字符串出现的次数)
startswith (判断字符串是否以指定值开始,返回布尔值)
endswith (判断字符串是否以指定值结束,返回布尔值)
find (在字符串中查找指定字符串,若找到,返回首次出现的索引,否则返回-1)
isalpha (判断字符串中是否全是字母)
isdecimal (判断字符是否全是十进制数)
isalnum (判断字符是否全是字母或数字)
lower (把字符串中所有字母改写成小写)
upper (把字符串中所有字母改写成大写)
replace (把字符串的旧字符替换成新字符) # 'kabisor'.replace('a', 'b')
strip (删除字符串头尾指定字符)
split (用指定分隔符分隔字符串,返回分隔片段列表)
splitlines (用于分隔多行字符串,返回每一行字符串组成的列表)
center (把字符串居中对齐到指定宽度) # 'kabisor'.center(10)
zfill (按指定宽度复制字符串,原字符串靠右对齐,前面填充0) # 'kabisor'.zfill(10)
splitlines() 多行字符串分隔
# splitlines()
multi_str = '''A:hellow!
B:hellow!
A:Nice to meet you.
B:Nice to meet you too.
'''
multi_str_split = multi_str.splitlines()
print(multi_str)
print(multi_str_split)
'''
A:hellow!
B:hellow!
A:Nice to meet you.
B:Nice to meet you too.
['A:hellow!', 'B:hellow!', 'A:Nice to meet you.', 'B:Nice to meet you too.']
'''
format() 字符串格式化
s = 'Some digits of pi:{}'
print(s.format(3.14159265359)) # Some digits of pi:3.14159265359
# 多次使用
s = 'My name is {0},I love {0}.'
print(s.format('Kabisor')) # My name is Kabisor,I love Kabisor
# 索引指定
s = 'My name is {0},I love {1}.'
print(s.format('Kabisor', 'Chen')) # My name is Kabisor,I love Chen.
# 变量指定
s = 'My name is {c},I love {k}.'
print(s.format(k='Kabisor', c='Chen')) # My name is Chen,I love Kabisor.
# 格式化数字时,千分位分隔符(逗号)
s = 'I have {:,}$.'
print(s.format(100000)) # I have 100,000$.
# 保留小数和转化成百分数
s = '{0:.4} = {0:.3%}'
print(s.format(0.078912)) # 0.07891 = 7.891%
网友评论