python字符串函数
作者:野牛程序员:2023-11-22 15:17:34python阅读 2662
python字符串函数:
capitalize: 首字母大写其余字母小写
s = "hello world" result = s.capitalize()
swapcase: 大小写翻转
s = "Hello World" result = s.swapcase()
title: 非字母隔开的每个单词的首字母大写
s = "hello world" result = s.title()
center: 设置总长度,并居中
s = "hello" result = s.center(10)
upper(): 全大写
s = "hello" result = s.upper()
lower(): 全小写
s = "HELLO" result = s.lower()
startswith: 检测字符串是否是由相同的开头,返回True或False
s = "hello world" result = s.startswith("hello")
endswith: 检测字符串是否是由相同的结尾,返回True或False
s = "hello world" result = s.endswith("world")
strip: 默认去除字符串前后的空格,换行符,制表符
s = " hello " result = s.strip()
lstrip(): 默认只去除左边的空格
s = " hello" result = s.lstrip()
rstrip(): 默认只去除右边的空格
s = "hello " result = s.rstrip()
replace: 字符串替换
s = "hello world" result = s.replace("world", "python")
split: 分隔,str ---> list
s = "hello world" result = s.split()
join: 分割,list---> str
my_list = ["hello", "world"] result = " ".join(my_list)
find: 通过元素找索引,找不到返回-1
s = "hello world" result = s.find("world")
index: 通过元素找索引,找不到会报错
s = "hello world" result = s.index("world")
len: 测量个数
s = "hello world" result = len(s)
count: (数)(方法统计某个元素在列表中出现的次数)
s = "hello world" result = s.count("l")
format: 格式化输出
name = "Alice" age = 25 result = "My name is {} and I am {} years old".format(name, age)
isalnum: 检验字符串是否由字母和数字组成
s = "hello123" result = s.isalnum()
isalpha: 检测字符串是否只由字母组成
s = "hello" result = s.isalpha()
isdigit: 检测字符串是否只由数字组成
s = "12345" result = s.isdigit()
sort(): 正序排序列表中的元素
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5] my_list.sort()
sort(): 倒叙排序列表中的元素
my_list = [3, 1, 4, 1, 5, 9, 2, 6, 5] my_list.sort(reverse=True)
reverse(): 翻转列表中的元素
my_list = [1, 2, 3, 4, 5] my_list.reverse()
野牛程序员教少儿编程与信息学奥赛-微信|电话:15892516892
