iT邦幫忙

2025 iThome 鐵人賽

DAY 7
0

今天來介紹字串,是一種用來表示文字資料的資料型態,在 Python 中只要看見放在""或是''之中的字元都視為字串,在前幾天的文章中有提到說單引號或是雙引號兩者功能是完全相同的,此外在 Python 中字串是不可變的!也就是說一但建立了,就無法直接修改其中的內容。

字串相加

在 python 中字串的連接可以直接使用加號 +合併。

first_name = "Jeter"
last_name = "Chen"
print(first_name + " " + last_name) # Jeter Chen

字串索引 index

在 Python 中索引計算是從0開始,因此字串的第一個字母為0索引,而字串的最後一個字母為字串的長度-1,以下使用索引位置取得資料

name = ["h", "e", "l", "l", "o"]
print(name[0])  # h
print(name[-1]) # o

字串切片 slice

語法:string[start:end:step]

  • srart:起始索引
  • end:結束索引(不包含)
  • stop:步數,預設為1不可為0
name = "hello world."
print(name[1:5]) # ello

基本上都是正序,如果想要將字串反轉可以使用[::-1]

name = "hello world."
print(name[::-1]) # .dlrow olleh

字串方法

Python 中提供許多方便的字串方法來處理文字,例如:

  • lower():轉換成小寫
text = "Hello World"
print(text.lower()) # hello world
  • upper():轉換成大寫
text = "Hello World"
print(text.upper()) # HELLO WORLD
  • strip():移除前後空白格或指定字元
    補充:lstriprstrip這兩個也是移除空白或是指定字元使用,差別在於前者移除左邊內容後者移除右邊的內容。
text = "   hello   "
print(text.strip()) # hello

text = "###hello###"
print(text.strip("#"))  # hello
text = "   hello   "
print(text.lstrip()) # "hello  "
print(text.rstrip()) # "  hello"
  • replace():取代
text = "abc"
print(text.replace("abc", "xyz"))  # xyz
  • split():將字串依照分割符號切割成列表
text = "apple, banana, cherry"
print(text.split(","))  # ["apple", "banana", "cherry"]
  • join():將指定分割符號把列表組合成字串
fruits = ["apple", "banana", "cherry"]
print(", ".join(fruits))  # apple, banana, cherry
  • index():搜尋字串位置
text = "My name is Jeter"
print(text.index("Jeter"))  # 11

f-string與字串格式化

字串格式化是將變數或表達式嵌入到字串中的方式,在 Python3.6 之後加入了f-string大幅提升可讀性及效能,且語法簡單

name = "Jeter"
age = 18
print(f"My name is {name}, and I'm {age} years old.")

那麼今天就介紹到這,明天見ㄅㄅ!


上一篇
筆記Day6:運算子 Operator
下一篇
筆記Day8:補充-字串 String
系列文
Python 學習筆記8
圖片
  熱門推薦
圖片
{{ item.channelVendor }} | {{ item.webinarstarted }} |
{{ formatDate(item.duration) }}
直播中

尚未有邦友留言

立即登入留言