字符串操作是Python中高频操作,灵活运用一些方法可以大大提升数据清洗,转换效率.
你对字符串的操作有多了解呢?本篇就细数下常见的字符串操作,也可以作为备忘录待需要时查询.
比较两个字符串是否相同
animals = ['python','gopher']more_animals = animalsprint(animals == more_animals) #=> Trueprint(animals is more_animals) #=> Trueeven_more_animals = ['python','gopher']print(animals == even_more_animals) #=> Trueprint(animals is even_more_animals) #=> False
在这里不要混淆了is和==运算符的用法,is是比较两个变量的内存地址是否相等,用id()可以查询变量的内存地址
print(id(animals))print(id(even_more_animals))
2.查询字符串中的每一个单词是否以大写字母开头istitle()函数查询字符串中的每一个单词是否以大写字母开头
print( 'The Hilton'.istitle() ) #=> Trueprint( 'The dog'.istitle() ) #=> Falseprint( 'sticky rice'.istitle() ) #=> False
3.检查字符串是否包含特定的子字符串
如果字符串包含子字符串,那么in操作符将返回True。
print( 'plane' in 'The worlds fastest plane' ) #=> Trueprint( 'car' in 'The worlds fastest plane' ) #=> False
4.查找字符串中第一次出现的子字符串的位置
可以使用find() 和 index()函数,两种方式的返回值有一点差别
find()会返回-1如果查找的子字符串没有找到
'The worlds fastest plane'.find('plane') #=> 19'The worlds fastest plane'.find('car') #=> -1
index()会抛出ValueError
'The worlds fastest plane'.index('plane') #=> 19'The worlds fastest plane'.index('car') #=> ValueError: substring not found
5.计算字符串的总长度
len()函数可以返回给定字符串的字符长度
len('The first president of the organization..') #=> 19
6.计算字符串中特定字符的数量
count()将返回特定字符的出现次数。
'The first president of the organization..'.count('o') #=> 3
7.将字符串的第一个字符大写
使用 capitalize()函数实现
'florida dolphins'.capitalize() #=> 'Florida dolphins'
8.使用f和占位符格式化输出字符串
在python 3.6中,f-string使得字符串插值变得非常简单。使用f-string类似于使用format()。
name = 'Chris'food = 'creme brulee'f'Hello. My name is {name} and I like {food}.'#=> 'Hello. My name is Chris and I like creme brulee'
9.在字符串的特定部分搜索子字符串
'the happiest person in the whole wide world.'.index('the',10,44)#=> 23'the happiest person in the whole wide world.'.index('the')#=> 0
10.使用format()将变量插入到字符串中
difficulty = 'easy'thing = 'exam''That {} was {}!'.format(thing, difficulty)#=> 'That exam was easy!'
11.检查字符串是否只包含数字
'80000'.isnumeric() #=> True'1.0'.isnumeric() #=> False
12.用特定字符分割字符串
'This is great'.split(' ')#=> ['This', 'is', 'great']'not--so--great'.split('--')#=> ['not', 'so', 'great']
13.检查一个字符串是否全部是小写字母组成
'all lower case'.islower() #=> True'not aLL lowercase'.islower() # False
14.检查字符串中的第一个字符是否是小写的
'aPPLE'[0].islower() #=> True
15.整数不可以和字符串直接相加
'Ten' + 10 #=> TypeError
16.反转字符串"helloworld"
''.join(reversed("hello world"))#=> 'dlrow olleh'"hello world"[::-1]#=> 'dlrow olleh'
17.使用特定字符将字符串列表连接为单个字符串
'-'.join(['a','b','c'])#=> 'a-b-c'
18.检查字符串中的所有字符是否符合ASCII
print( 'Â'.isascii() ) #=> Falseprint( 'A'.isascii() ) #=> True
19.大写或小写整个字符串
sentence = 'The Cat in the Hat'sentence.upper() #=> 'THE CAT IN THE HAT'sentence.lower() #=> 'the cat in the hat'
20.字符串的第一个和最后一个字符转为大写
animal = 'fish'animal[0].upper() + animal[1:-1] + animal[-1].upper()#=> 'FisH'
21.检查一个字符串是否全大写
'Toronto'.isupper() #=> False'TORONTO'.isupper() #= True
22.使用splitlines()在换行符上分割字符串
sentence = "It was a stormy night\nThe house creeked\nThe wind blew."sentence.splitlines()#=> ['It was a stormy night', 'The house creeked', 'The wind blew.']
23.字符串切片操作
string = 'I like to eat apples'string[:6] #=> 'I like'string[7:13] #=> 'to eat'string[0:-1:2] #=> 'Ilk oetape' (every 2nd character)
24.将整数转换为字符串
str(5) #=> '5'
25.检查一个字符串是否只包含字母表中的字符
'One1'.isalpha() #=> False'One'.isalpha() #=> True
26.用指定的子字符串替换字符串中的所有相同的子串
sentence = 'Sally sells sea shells by the sea shore'sentence.replace('sea', 'mountain')#=> 'Sally sells mountain shells by the mountain shore'
27.返回字符串中索引最小的字符
min('strings') #=> 'g'
28.检查字符串中的所有字符是否都是字母或数字
'Ten10'.isalnum() #=> True'Ten10.'.isalnum() #=> False
29.删除字符串左、右或两边的空白
string = ' string of whitespace 'string.lstrip() #=> 'string of whitespace 'string.rstrip() #=> ' string of whitespace'string.strip() #=> 'string of whitespace''10$'.strip('$') #=>10
30.检查字符串是否以特定字符开始或结束
city = 'New York'city.startswith('New') #=> Truecity.endswith('N') #=> False
31.检查所有字符是否都是空格字符
''.isspace() #=> False' '.isspace() #=> True' '.isspace() #=> True' the '.isspace() #=> False
32.将字符串重复n次并连接
'dog' * 3# 'dogdogdog'
33.将字符串中每个单词的第一个字符转为大写
'once upon a time'.title()#'Once Upon A Time'
34.字符串连接
'string one' + ' ' + 'string two' #=> 'string one string two'
35.partition()函数示例
partition()在子字符串的第一个实例上拆分字符串。返回拆分字符串的元组,而不删除子字符串。
sentence = "If you want to be a ninja"print(sentence.partition(' want '))#=> ('If you', ' want ', 'to be a ninja')
36.内存地址比较
两个字符串变量赋值相同,使用相同的内存地址,Python的节约内存机制
animal = 'dog'print( id(animal) )#=> 4441985688pet = 'dog'print( id(pet) )#=> 4441985688
37.从字符串的右侧开始搜索,并返回第一个匹配的子字符串的位置
story = 'The price is right said Bob. The price is right.'story.rfind('is')#=> 39
38.检查字符串是否为浮点数
number='3.14159256'try: number = float("number")except ValueError: print ("not a number")# "not a number"
39.检查字符串中的所有字符是否都是字母
'abcd'.isalpha() #=> True'abc123'.isalpha() #=> False
40.检查字符串中的所有字符是否都是数字
'12345'.isdigit() #=> True'12345'.isnumeric() #=> True'二十'.isnumeric() #=> True'3.14'.isdigit() #=> False