在Python中,str是一個內置的字符串類,可以用于表示和操作字符串。以下是一些常用的str方法和操作:
s1 = 'Hello, World!' # 使用單引號創建字符串
s2 = "Hello, World!" # 使用雙引號創建字符串
s3 = """Hello,
World!""" # 使用三引號創建多行字符串
s = "Hello, World!"
print(s[0]) # 輸出:H
print(s[7]) # 輸出:W
s = "Hello, World!"
print(len(s)) # 輸出:13
s = "Hello, World!"
print(s[0:5]) # 輸出:Hello
print(s[7:]) # 輸出:World!
s1 = "Hello"
s2 = "World"
s3 = s1 + " " + s2
print(s3) # 輸出:Hello World
name = "Alice"
age = 25
s = "My name is {} and I am {} years old.".format(name, age)
print(s) # 輸出:My name is Alice and I am 25 years old.
s = "Hello, World!"
print(s.upper()) # 輸出:HELLO, WORLD!
print(s.lower()) # 輸出:hello, world!
print(s.replace("Hello", "Hi")) # 輸出:Hi, World!
print(s.split(",")) # 輸出:['Hello', ' World!']
這只是字符串操作的一部分,str類還有許多其他方法和功能。你可以查閱Python官方文檔以獲取更詳細的信息。