Python中的str類型是用來表示字符串的數(shù)據(jù)類型,可以幫助處理文本數(shù)據(jù)。以下是一些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
通過以上方法,可以方便地處理文本數(shù)據(jù),進(jìn)行字符串的拼接、格式化、查找、替換、分割和大小寫轉(zhuǎn)換等操作。