2字符串常见函数操作

字符串常见函数操作
find()
例:my_str = "hello world"
my_str.find("world") 为6,world的首字符下标
rfind 从右边开始找
找不到则返回-1
 
index同find,但找不到则报错
 
count
找字符串的次数
 
replace()
my_str = "hello world world"
my_str.replace("world","haha")结果为“hello haha haha“
my_str.replace("world","haha",1)结果为“hello haha world“
 
split()
my_str.split (“ ”) :“hello”,"world","world"
my_str.split(“ll”) : "he","o world world"
还可以类似my_str.split ( "or",1) 即只分割1个
 
partition()
my_str.partition() = "ll" : "he", "ll" ,"o world world"
rpartition()
 
capitalize
把字符串首字母大写
 
title()
把字符串每个单词首字符大写
 
startswith()
检查字符串是否以obj为开头,返回Ture,False
endswith()
 
lower()
把字符串所有字母变为小写
upper()
 
ljust()
返回一个原字符串左对齐,并使用空格填充至长度with的新字符串
rjust
center()
例:print("hello world".center(30))
strip()
去掉字符串左右两边的空格
lstrip()
rstrip()
 
isalpha()
如果字符串全是字母,返回Ture,否则False
 
isdigit()
 
isalnum()
字母或数字
 
join()例:
names = ["100","200"."300"]
"".join(names) : ’100200300‘
把空字符串加到上面每个字符串后面然后连起来,可以是其他的“-”
 
查询help
例help(name.find)
 
面试题 给定一个字符串,返回使用空格或\t分割后的倒数第二个字符串
例:names = "fajl fdslakf fd\tdsfsdaj"
name.split()[-2]
 

猜你喜欢

转载自www.cnblogs.com/huangguoming/p/9900374.html