欢迎访问宙启技术站
智能推送

Python常用的字符串处理函数:split、join、strip、replace等

发布时间:2023-06-17 22:35:39

Python是一种简单易学的编程语言,常用于数据科学和文本处理,针对字符串处理,Python提供了一系列的字符串处理函数。本文将介绍Python中常用的字符串处理函数,包括split、join、strip、replace等函数。

1. split函数

split函数是将字符串分割成一个列表(list),并以指定的字符或字符串作为分割符。默认的分隔符是空格,可以使用split函数中的参数进行自定义分隔。

例如:

str = "hello world"
str_list = str.split() # 默认以空格为分隔符
print(str_list)

Output: ['hello', 'world']

str = "1,2,3,4,5"
str_list = str.split(",")
print(str_list)

Output: ['1', '2', '3', '4', '5']

2. join函数

join函数用于将一个列表(list)中的所有字符串元素合并为一个字符串,并以指定的字符或字符串作为连接符。

例如:

str_list = ['hello', 'world']
str_connect = ' '.join(str_list) # 使用空格连接字符串元素
print(str_connect)

Output: 'hello world'

str_list = ['1', '2', '3', '4', '5']
str_connect = '-'.join(str_list) # 使用-连接字符串元素
print(str_connect)

Output: '1-2-3-4-5'

3. strip函数

strip函数用于去除字符串开头和结尾的空白字符,包括空格、制表符、换行符等。当传入参数时,将去除指定的字符或字符串。

例如:

str = "   hello world 
"
str_strip = str.strip() # 去除空白字符
print(str_strip)

Output: 'hello world'

str = "%%%hello world%%%***"
str_strip = str.strip('%*') # 去除%%%和***字符
print(str_strip)

Output: 'hello world'

4. replace函数

replace函数用于替换字符串中的指定子串。可以指定替换所有出现的子串,也可以指定替换前n个子串。

例如:

str = "hello python"
str_replace = str.replace('python', 'world') # 将python替换为world
print(str_replace)

Output: 'hello world'

str = "1,1,2,3,3,3,4,4,5"
str_replace = str.replace('3', 'three', 2) # 将前两个3替换为three
print(str_replace)

Output: '1,1,2,three,three,3,4,4,5'

5. capitalize函数

capitalize函数用于将字符串的首字母大写。

例如:

str = "hello world"
str_cap = str.capitalize() # 将h变为大写H
print(str_cap)

Output: 'Hello world'

6. lower函数

lower函数用于将字符串中所有字符转换为小写字母。

例如:

str = "Hello world"
str_lower = str.lower() # 将所有字符转换为小写
print(str_lower)

Output: 'hello world'

7. upper函数

upper函数用于将字符串中所有字符转换为大写字母。

例如:

str = "Hello world"
str_upper = str.upper() # 将所有字符转换为大写
print(str_upper)

Output: 'HELLO WORLD'

8. count函数

count函数用于统计字符串中指定子串的出现次数。

例如:

str = "hello python, I love python"
count = str.count('python') # 统计python出现的次数
print(count)

Output: 2

总结

以上就是Python中常用的字符串处理函数,包括split、join、strip、replace等常规操作,掌握这些函数能帮助你更加高效地处理字符串数据。