利用Python字符串操作函数进行文本处理
发布时间:2023-07-03 11:57:21
Python字符串操作函数是非常强大的,可以帮助我们进行各种文本处理任务。下面是一些常用的Python字符串操作函数和示例:
1. len() 函数:可以用于获取字符串的长度。
string = "Hello World" length = len(string) print(length)
输出结果为:11
2. upper() 函数:可以将字符串转换为大写。
string = "Hello World" new_string = string.upper() print(new_string)
输出结果为:HELLO WORLD
3. lower() 函数:可以将字符串转换为小写。
string = "Hello World" new_string = string.lower() print(new_string)
输出结果为:hello world
4. capitalize() 函数:可以将字符串的 个字符转换为大写,其他字符转换为小写。
string = "hello world" new_string = string.capitalize() print(new_string)
输出结果为:Hello world
5. swapcase() 函数:可以将字符串中的大写字母转换为小写,小写字母转换为大写。
string = "Hello World" new_string = string.swapcase() print(new_string)
输出结果为:hELLO wORLD
6. strip() 函数:可以用于去除字符串两边的空格。
string = " Hello World " new_string = string.strip() print(new_string)
输出结果为:Hello World
7. split() 函数:可以将字符串分割成一个列表,可以指定分割符。
string = "Hello,World,Python"
new_string = string.split(",")
print(new_string)
输出结果为:['Hello', 'World', 'Python']
8. join() 函数:可以将列表中的字符串连接成一个新的字符串,可以指定连接符。
string_list = ['Hello', 'World', 'Python'] new_string = ",".join(string_list) print(new_string)
输出结果为:Hello,World,Python
9. replace() 函数:可以替换字符串中的指定字符。
string = "Hello World"
new_string = string.replace("World", "Python")
print(new_string)
输出结果为:Hello Python
10. find() 函数:可以查找子字符串在字符串中的位置,如果找到返回索引,否则返回-1。
string = "Hello World"
index = string.find("World")
print(index)
输出结果为:6
这些函数只是Python字符串操作的一小部分,Python还有很多其他强大的字符串操作函数可以帮助我们进行更复杂的文本处理任务。
