首頁>技術>

string

python 中的 string 字串要麼是以 單引號 要麼是 雙引號 表示的,比如說:'hello' 和 "hello" 是一個意思,也可以直接使用 print 列印字串。

print("Hello")print('Hello')
將 string 賦給變數

將一個字串賦給一個變數可以使用下面的賦值語句。

a = "Hello"print(a)
多行string

可以使用三個雙引號的多行字串格式賦給一個變數,如下所示:

a = """Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididuntut labore et dolore magna aliqua."""print(a)PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyLorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididuntut labore et dolore magna aliqua.

同樣也可以使用三個單引號方式。

a = '''Lorem ipsum dolor sit amet,consectetur adipiscing elit,sed do eiusmod tempor incididuntut labore et dolore magna aliqua.'''print(a)
string 和 array

像很多程式語言一樣, python 中的字串也是用 unicode 表示的位元組陣列,但是 Python 中並沒有字元型別,因為 python 中的單引號和雙引號都表示字串。

使用 [] 的形式可以訪問 string 中的元素,比如獲取下面string 中的第一個字元。

a = "Hello, World!"print(a[1])
迴圈string

因為 string 是一個 array,所以我們可以使用 迴圈 來迭代string中的字元,python 中 使用 for 迴圈即可。

for x in "banana":  print(x)
string 長度

可以用 len() 函式獲取 string 的長度

a = "Hello, World!"print(len(a))
字串檢查

如何想檢查 一個短語 或者 一個字元 是否為某一個字串的子集,可以使用 in 運算子。

txt = "The best things in life are free!"print("free" in txt)---- output ----PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyTrue

也可以將 in 和 if 搭配使用,實現條件判斷邏輯。

txt = "The best things in life are free!"if "free" in txt:  print("Yes, 'free' is present.")--- output ---PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyYes, 'free' is present.

同樣的道理,可以使用 if not 實現上面情況的反向操作。

txt = "The best things in life are free!"print("expensive" not in txt)txt = "The best things in life are free!"if "expensive" not in txt:  print("Yes, 'expensive' is NOT present.")--- output ---PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyTrueYes, 'expensive' is NOT present.
切片操作

使用 切片 語法 可以實現從一個 string 中返回一個範圍的子字串。

透過指定切片的三元素:起始,結束 和 ":" ,來返回 string 的一部分,舉個例子:從下面字串中切下 第 2-5 位置的子串。

b = "Hello, World!"print(b[2:5])---- output ----PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyllo
從 start 位置切片

如果忽略開始位置的話,這個切片範圍預設會從第一個字元開始,下面的例子和上面是一樣的。

b = "Hello, World!"print(b[:5])
從 end 位置切片

如果忽略結束位置的話,這個切片範圍預設會到 string 的末尾,比如下面的例子中從 string 的第二個位置開始切下字串。

b = "Hello, World!"print(b[2:])
負數索引

負數表示從 string 的末尾往前開始計算位置,舉個例子:

b = "Hello, World!"print(b[-5:-2])--- output ---PS E:\dream\markdown\python> & "C:/Program Files (x86)/Python/python.exe" e:/dream/markdown/python/app/app.pyorl

稍微解釋一下:

13
最新評論
  • BSA-TRITC(10mg/ml) TRITC-BSA 牛血清白蛋白改性標記羅丹明
  • Python 入門系列——8. 型別轉換