Python中字符串的常用函数及用法
发布时间:2023-05-23 06:54:12
Python中字符串是一种不可变的数据类型,一旦定义后就无法改变。字符串是由一系列字符组成的,可以使用一些字符串常用函数来操作和处理。
1. len():获取字符串的长度,返回一个整数值。
示例代码:
s = 'hello,world' print(len(s)) # 输出 11
2. count():统计某个字符或字符串在字符串中出现的次数,返回一个整数值。
示例代码:
s = 'hello,world'
print(s.count('l')) # 输出 3
print(s.count('lo')) # 输出 1
3. find():查找某个字符或字符串在字符串中出现的位置,返回 次出现的位置的索引值,如果没有找到则返回-1。
示例代码:
s = 'hello,world'
print(s.find('l')) # 输出 2
print(s.find('lo')) # 输出 3
print(s.find('k')) # 输出 -1
4. replace():替换字符串中的某个字符或字符串为另一个字符或字符串。
示例代码:
s = 'hello,world'
print(s.replace('l', 'L')) # 输出 heLLo,wordL
print(s.replace('world', 'Python')) # 输出 hello,Python
5. split():分割字符串,返回一个由子字符串组成的列表。
示例代码:
s = 'hello,world'
print(s.split(',')) # 输出 ['hello', 'world']
6. join():连接字符串,将一个列表中的字符串连接起来。
示例代码:
lst = ['hello', 'world'] s = '-'.join(lst) print(s) # 输出 hello-world
7. upper():将字符串中的所有字符转换为大写字母。
示例代码:
s = 'hello,world' print(s.upper()) # 输出 HELLO,WORLD
8. lower():将字符串中的所有字符转换为小写字母。
示例代码:
s = 'HELLO,WORLD' print(s.lower()) # 输出 hello,world
9. capitalize():将字符串中的 个字符转换为大写字母,其他字符全部转换为小写字母。
示例代码:
s = 'hello,world' print(s.capitalize()) # 输出 Hello,world
10. strip():去掉字符串开头和结尾的空格或指定的字符。
示例代码:
s = ' hello,world '
print(s.strip()) # 输出 hello,world
print(s.strip(' l')) # 输出 heo,world
这些字符串常用函数可以用来对字符串进行处理和操作,使得程序更加方便和高效。
