当前位置:首页python > 正文

python字符串函数

作者:野牛程序员:2023-11-22 15:17:34python阅读 2626

python字符串函数:

capitalize: 首字母大写其余字母小写

1
2
= "hello world"
result = s.capitalize()

swapcase: 大小写翻转

1
2
= "Hello World"
result = s.swapcase()

title: 非字母隔开的每个单词的首字母大写

1
2
= "hello world"
result = s.title()

center: 设置总长度,并居中

1
2
= "hello"
result = s.center(10)

upper(): 全大写

1
2
= "hello"
result = s.upper()

lower(): 全小写

1
2
= "HELLO"
result = s.lower()

startswith: 检测字符串是否是由相同的开头,返回True或False

1
2
= "hello world"
result = s.startswith("hello")

endswith: 检测字符串是否是由相同的结尾,返回True或False

1
2
= "hello world"
result = s.endswith("world")

strip: 默认去除字符串前后的空格,换行符,制表符

1
2
= "  hello  "
result = s.strip()

lstrip(): 默认只去除左边的空格

1
2
= "  hello"
result = s.lstrip()

rstrip(): 默认只去除右边的空格

1
2
= "hello  "
result = s.rstrip()

replace: 字符串替换

1
2
= "hello world"
result = s.replace("world""python")

split: 分隔,str ---> list

1
2
= "hello world"
result = s.split()

join: 分割,list---> str

1
2
my_list = ["hello""world"]
result = " ".join(my_list)

find: 通过元素找索引,找不到返回-1

1
2
= "hello world"
result = s.find("world")

index: 通过元素找索引,找不到会报错

1
2
= "hello world"
result = s.index("world")

len: 测量个数

1
2
= "hello world"
result = len(s)

count: (数)(方法统计某个元素在列表中出现的次数)

1
2
= "hello world"
result = s.count("l")

format: 格式化输出

1
2
3
name = "Alice"
age = 25
result = "My name is {} and I am {} years old".format(name, age)

isalnum: 检验字符串是否由字母和数字组成

1
2
= "hello123"
result = s.isalnum()

isalpha: 检测字符串是否只由字母组成

1
2
= "hello"
result = s.isalpha()

isdigit: 检测字符串是否只由数字组成

1
2
= "12345"
result = s.isdigit()

sort(): 正序排序列表中的元素

1
2
my_list = [314159265]
my_list.sort()

sort(): 倒叙排序列表中的元素

1
2
my_list = [314159265]
my_list.sort(reverse=True)

reverse(): 翻转列表中的元素

1
2
my_list = [12345]
my_list.reverse()


野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
野牛程序员教少儿编程与信息学竞赛-微信|电话:15892516892
相关推荐

最新推荐

热门点击