今天來介紹字串,是一種用來表示文字資料的資料型態,在 Python 中只要看見放在""
或是''
之中的字元都視為字串,在前幾天的文章中有提到說單引號
或是雙引號
兩者功能是完全相同的,此外在 Python 中字串是不可變的!也就是說一但建立了,就無法直接修改其中的內容。
在 python 中字串的連接可以直接使用加號 +
合併。
first_name = "Jeter"
last_name = "Chen"
print(first_name + " " + last_name) # Jeter Chen
在 Python 中索引計算是從0
開始,因此字串的第一個字母為0索引,而字串的最後一個字母為字串的長度-1,以下使用索引位置取得資料
name = ["h", "e", "l", "l", "o"]
print(name[0]) # h
print(name[-1]) # o
語法:string[start:end:step]
name = "hello world."
print(name[1:5]) # ello
基本上都是正序,如果想要將字串反轉可以使用[::-1]
name = "hello world."
print(name[::-1]) # .dlrow olleh
Python 中提供許多方便的字串方法來處理文字,例如:
text = "Hello World"
print(text.lower()) # hello world
text = "Hello World"
print(text.upper()) # HELLO WORLD
lstrip
和rstrip
這兩個也是移除空白或是指定字元使用,差別在於前者移除左邊內容後者移除右邊的內容。text = " hello "
print(text.strip()) # hello
text = "###hello###"
print(text.strip("#")) # hello
text = " hello "
print(text.lstrip()) # "hello "
print(text.rstrip()) # " hello"
text = "abc"
print(text.replace("abc", "xyz")) # xyz
text = "apple, banana, cherry"
print(text.split(",")) # ["apple", "banana", "cherry"]
fruits = ["apple", "banana", "cherry"]
print(", ".join(fruits)) # apple, banana, cherry
text = "My name is Jeter"
print(text.index("Jeter")) # 11
字串格式化是將變數或表達式嵌入到字串中的方式,在 Python3.6 之後加入了f-string
大幅提升可讀性及效能,且語法簡單
name = "Jeter"
age = 18
print(f"My name is {name}, and I'm {age} years old.")
那麼今天就介紹到這,明天見ㄅㄅ!