Python 字串
字串
Python 中的字串可以用單引號或雙引號括起來。
'hello' 和 "hello" 是相同的。
您可以使用 print()
函式顯示字串字面量
引號中的引號
你可以在字串中使用引號,只要它們不與包圍字串的引號匹配
為變數賦字串值
將字串賦給變數,變數名後跟等號,然後是字串。
多行字串
您可以使用三個引號來為變數賦值多行字串
示例
您可以使用三個雙引號
a = """Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua."""
print(a)
自己動手試一試 »
或者三個單引號
示例
a = '''Lorem ipsum dolor sit amet,
consectetur adipiscing elit,
sed do eiusmod tempor incididunt
ut labore et dolore magna aliqua.'''
print(a)
自己動手試一試 »
注意: 在結果中,換行符會插入到程式碼中相同的位置。
字串是陣列
像許多其他流行的程式語言一樣,Python 中的字串是表示 Unicode 字元的位元組陣列。
但是,Python 沒有字元資料型別,單個字元只是一個長度為 1 的字串。
可以使用方括號訪問字串的元素。
遍歷字串
由於字串是陣列,我們可以透過 for
迴圈遍歷字串中的字元。
在我們的 Python For Loops 章節中瞭解更多關於 For Loops 的資訊。
字串長度
要獲取字串的長度,請使用 len()
函式。
檢查字串
要檢查某個短語或字元是否存在於字串中,我們可以使用關鍵字 in
。
在 if
語句中使用它
示例
僅當“free”存在時列印
txt = "The best things in life are free!"
if "free" in txt
print("Yes, 'free' is present.")
自己動手試一試 »
在我們的 Python If...Else 章節中瞭解更多關於 If 語句的資訊。
檢查是否不存在
要檢查某個短語或字元是否不在字串中,我們可以使用關鍵字 not in
。
示例
檢查“expensive”是否不存在於以下文字中
txt = "The best things in life are free!"
print("expensive" not in txt)
自己動手試一試 »
在 if
語句中使用它
示例
僅當“expensive”不存在時列印
txt = "The best things in life are free!"
if "expensive" not in txt
print("No, 'expensive' is NOT present.")
自己動手試一試 »