1.常用的字符串函数
line = " hello world,I am python. \n\t"
line.capitalize() #将第一个字符大写,其他字符均为大写
line.center(20) #将字符串居中并打印(字符串长度为20)
line.center(20,'%') #不加字符串默认是空格补全,此就是用%替代空格补全
line.count('w') #计算w在line中出现的次数
line.endswith('huan') #判断字符串是否以huan结尾
line.startswith('huan') #判断字符串是否以huan开头
line.find('h') #查找字符串并返回下标,当字符串不存在时返回-1
line.index('h') #查找字符串并返回下标,当字符不存在时报错
line.upper() #将所有字符大写
line.lower() #将所有字符小写
line.swapcase() #大写变小写,小写变大写
line.istitle() #判断line是否是标题(首字符大写,其他字符均为小写)
line.isupper() #判断所有字符是否都为大写
line.islower() #判断所有字符是否都为小写
line.strip() #去除两端的空格或者制表符、换行符等无效字符
line.rstrip() #去除右边的空格或者制表符、换行符等无效字符
line.rstrip() #去除左边的空格或者制表符、换行符等无效字符
上面我们用到的所有字符串函数,都是为我们生成了一个新的字符串,原有的字符串是不变的,用以下代码可以进行验证
line = 'hello,jeams'
id(line)
new_line = line.upper() #可以更换其他字符串函数进行测试
id(line)
id(new_line)
2.格式化字符串 f-string(最低 Python 版本为 3.6)
大多数使用 Python 的人会偏向于使用「format」方法。
user = "jevon"
area = "China"
long_message_1 = 'I am {} and I come from {}.'.format(
user,
area
)
print(long_message_1)
除了「format」,Python 3 还提供了一种通过「f-string」进行字符串插入的灵活方法。
user = "jevon"
area = "China"
long_message_2 = f'I am {user} and I come from {area}.'
print(long_message_2)