Python中str是一種字符串類型的數據結構,用于表示文本信息。可以通過以下方式使用str:
s = "Hello, World!"
print(s[0]) # 輸出:H
print(len(s)) # 輸出:13
print(s[7:12]) # 輸出:World
s1 = "Hello"
s2 = "World"
s3 = s1 + ", " + s2
print(s3) # 輸出:Hello, World
name = "Alice"
age = 25
print("My name is %s and I'm %d years old." % (name, age)) # 輸出:My name is Alice and I'm 25 years old.
s = "Hello, World!"
print(s.find("World")) # 輸出:7
print(s.replace("Hello", "Hi")) # 輸出:Hi, World!
s = "Hello"
print(s.lower()) # 輸出:hello
print(s.upper()) # 輸出:HELLO
s = "Hello, World!"
print(s.split(",")) # 輸出:['Hello', ' World!']
print(" ".join(['Hello', 'World!'])) # 輸出:Hello World!
s = "Hello, World!"
print(s.startswith("Hello")) # 輸出:True
print(s.endswith("World!")) # 輸出:True
這些是常見的字符串操作方法,可以根據需要來使用。