python字符串常用操作

a = ‘Hello world’

upper全部大写

print(a.upper()) ==》HELLO WORLD

lower全部小写

print(a.lower()) ==》hello world

title首字母大写

print(a.title()) ==》Hello World

capitalize首字母变大写

print(a.capitalize()) ==》Hello world

swapcase大写变小写。小写变大写

print(a.swapcase())

count统计字符出现的次数

print(a.count(‘o’)) ==》2

replace替换字符

b= a.replace(‘world’,‘python’)

print(b) ==》Hello python

find 查找指定字符 ==》找到该字符串的索引位置。如果找不到就返回-1

index1= a.find(‘wo’)

index2= a.find(‘ow’)

print(index1) ==》6

print(index2) ==》-1

index 方法如果找不到就会报错 ValueError值错误

result1= a.index(‘wo’)

result2= a.index(‘ow’)

print(result1,result2) ==》ValueError

join 组合,连接字符串数组。将字符串、元组、列表中的元素以指定的字符(分隔符)连接生成一个新的字符串

person_info= [‘Tom’,‘男’,‘27’,‘180’]

person_info= ‘,’.join(person_info)

print(person_info) ==》Tom,男,27,180

split 拆分,按某一个字符分割,且分割n次

person_info1= (‘hello,world’)

person_info1= person_info1.split(’,’)

print(person_info1) ==》 [‘hello’, ‘world’]

strip 去掉头和尾指定的字符,中间无法去除

d= ‘666Helleo 6 python!666’

f= d.strip(‘6’)

print(f) ==》Helleo 6 python!

你可能感兴趣的:(python)