Modify Srings()
Upper Case
a = "Hello, World!"
print(a.upper())
output :
HELLO, WORLD!
Lower Case
a = "Hello, World!"
print(a.lower())
output :
hello, world!
Remove Whitespace
removes any whitespace from the beginning or the end移除字串開頭與結尾的所有空白字元(包含空格與跳行符號等)。
a = " Hello, World! "
print(a.strip()) # returns "Hello, World!"
Replace String
將字串中所有指定的子字串替換為新的內容。
a = "Hello, World!"
print(a.replace("H", "J"))
output :
Jello, World!
Split String
splits the string into substrings if it finds instances of the separator:
依指定分隔符號(如逗號)將字串切割為多個子字串,回傳串列(list)
a = "Hello, World!"
print(a.split(",")) # returns ['Hello', ' World!']
output :
['Hello', ' World!']
String Concatenation(字串串接)
To concatenate, or combine, two strings you can use the + operator.
要合併(串接)兩個字串,可以使用 +
運算子。
greeting = "Welcome,"
user = "Alice"
message = greeting + " " + user + "!"
print(message) # 輸出:Welcome, Alice!
subject = "Math"
score = "90"
result = subject + ": " + score
print(result) # 輸出:Math: 90