Python中的str类型是用来表示字符串的数据类型,可以帮助处理文本数据。以下是一些str类型的常用方法:
str1 = "Hello"
str2 = "World"
result = str1 + " " + str2
print(result) # 输出:Hello World
name = "Alice"
age = 30
result = "My name is {} and I am {} years old".format(name, age)
print(result) # 输出:My name is Alice and I am 30 years old
result = f"My name is {name} and I am {age} years old"
print(result) # 输出:My name is Alice and I am 30 years old
text = "Hello World"
print(text.find("World")) # 输出:6
print(text.index("World")) # 输出:6
print(text.startswith("Hello")) # 输出:True
print(text.endswith("World")) # 输出:True
text = "Hello World"
new_text = text.replace("World", "Python")
print(new_text) # 输出:Hello Python
text = "Hello,World"
result = text.split(",")
print(result) # 输出:['Hello', 'World']
text = "Hello World"
print(text.lower()) # 输出:hello world
print(text.upper()) # 输出:HELLO WORLD
print(text.capitalize()) # 输出:Hello world
通过以上方法,可以方便地处理文本数据,进行字符串的拼接、格式化、查找、替换、分割和大小写转换等操作。