在Python中,我们可以使用丰富的文本处理和字符串函数来轻松操纵文本数据。下面介绍一些常用的方法和函数,以及它们的用法和示例。
1、基本操作:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2 # "Hello World"
text = "Hello World"
length = len(text) # 11
text = "apple,banana,orange"
fruits = text.split(",") # ['apple', 'banana', 'orange']
text = "Hello World"
upper_text = text.upper() # "HELLO WORLD"
lower_text = text.lower() # "hello world"
2、查找和替换:
text = "Hello World"
index = text.find("World") # 6
text = "Hello World"
new_text = text.replace("World", "Python") # "Hello Python"
3、格式化:
name = "Alice"
age = 25
message = "My name is {}, and I am {} years old.".format(name, age)
# "My name is Alice, and I am 25 years old."
name = "Bob"
age = 30
message = f"My name is {name}, and I am {age} years old."
# "My name is Bob, and I am 30 years old."
4、正则表达式:
import re
text = "Hello 123 World"
pattern = r"\d+" # 匹配连续的数字
matches = re.findall(pattern, text) # ['123']
详细的正则表达式语法请查阅相关文档或教程以深入了解。
这些是Python中常用的文本处理和字符串函数。使用这些函数和方法,您可以轻松操纵文本数据,实现字符串拼接、分割、查找、替换、格式化等操作。