Python中常用的字符串处理函数:split()、join()等
发布时间:2023-10-28 20:38:23
Python是一种非常强大的编程语言,提供了许多用于字符串处理的内置函数。下面将介绍一些常用的字符串处理函数。
1. split():用于将字符串根据指定的分隔符分割成多个子字符串,并返回一个包含所有子字符串的列表。例如:
s = "hello world" result = s.split() # 分割字符串,默认以空格分隔 print(result) # 输出: ['hello', 'world']
2. join():用于将列表中的字符串按照指定的分隔符连接成一个新的字符串。例如:
s = ['hello', 'world'] result = ' '.join(s) # 以空格为分隔符连接字符串 print(result) # 输出: 'hello world'
3. strip():用于移除字符串开头和结尾的指定字符(默认为空格)。例如:
s = " hello world " result = s.strip() # 移除首尾空格 print(result) # 输出: 'hello world'
4. replace():用于将字符串中的指定字符替换成新的字符。例如:
s = "hello world"
result = s.replace('o', '0') # 将字符串中的'o'替换为'0'
print(result) # 输出: 'hell0 w0rld'
5. find():用于返回指定字符(子字符串)在字符串中 次出现的位置。如果未找到则返回-1。例如:
s = "hello world"
result = s.find('o') # 查找'o'在字符串中的位置
print(result) # 输出: 4
6. count():用于返回指定字符(子字符串)在字符串中出现的次数。例如:
s = "hello world"
result = s.count('l') # 统计字符串中'l'的出现次数
print(result) # 输出: 3
7. lower()和upper():分别用于将字符串中的字母转为小写和大写。例如:
s = "Hello World" result1 = s.lower() # 将字符串转为小写 result2 = s.upper() # 将字符串转为大写 print(result1) # 输出: 'hello world' print(result2) # 输出: 'HELLO WORLD'
8. startswith()和endswith():分别用于判断字符串是否以指定的字符(子字符串)开头或结尾,返回True或False。例如:
s = "hello world"
result1 = s.startswith('hello') # 判断字符串是否以'hello'开头
result2 = s.endswith('world') # 判断字符串是否以'world'结尾
print(result1) # 输出: True
print(result2) # 输出: True
这里只列举了Python中常用的字符串处理函数的一部分,还有许多其他有用的函数可供使用。字符串处理在编程中经常使用,掌握这些函数可以提高代码的效率和可读性。
