Python 字串 (String)

字串是用來儲存文字的資料型別,用單引號 ' 或雙引號 " 包起來。

建立字串

# 單引號
name = 'Alice'

# 雙引號
greeting = "Hello, World!"

# 兩者沒有區別,選擇一種風格即可

當字串中包含引號時,可以交替使用:

# 字串包含單引號,用雙引號包圍
message = "It's a beautiful day"

# 字串包含雙引號,用單引號包圍
quote = 'He said "Hello"'

# 或使用跳脫字元
message = 'It\'s a beautiful day'

多行字串

使用三個引號 '''""" 建立多行字串:

text = """這是一個
多行字串
可以跨越多行"""

print(text)

輸出:

這是一個
多行字串
可以跨越多行

跳脫字元

跳脫字元說明
\\反斜線
\'單引號
\"雙引號
\n換行
\tTab
\r歸位
print("Hello\nWorld")  # 換行
print("Hello\tWorld")  # Tab
print("C:\\Users\\Name")  # 反斜線

Raw String

在字串前加上 r,跳脫字元不會被處理:

# 一般字串
print("C:\new\folder")  # \n 會被當成換行

# Raw string
print(r"C:\new\folder")  # 輸出: C:\new\folder

字串索引

字串中的每個字元都有一個索引位置,從 0 開始:

text = "Python"
#       012345

print(text[0])   # P
print(text[1])   # y
print(text[-1])  # n(負數從尾端算起)
print(text[-2])  # o

字串切片 (Slicing)

語法:字串[start:end:step]

text = "Hello, World!"

print(text[0:5])    # Hello(索引 0 到 4)
print(text[7:12])   # World
print(text[:5])     # Hello(從開頭到索引 4)
print(text[7:])     # World!(從索引 7 到結尾)
print(text[::2])    # Hlo ol!(每隔一個字元)
print(text[::-1])   # !dlroW ,olleH(反轉字串)

字串長度

text = "Hello"
print(len(text))  # 5

字串連接

first = "Hello"
second = "World"

# 用 + 連接
result = first + " " + second
print(result)  # Hello World

# 用 join 連接
words = ["Hello", "World"]
result = " ".join(words)
print(result)  # Hello World

字串重複

text = "Ha"
print(text * 3)  # HaHaHa

檢查子字串

text = "Hello, World!"

print("Hello" in text)      # True
print("Python" in text)     # False
print("Python" not in text) # True

字串格式化

f-string(推薦)

name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

format() 方法

print("My name is {} and I am {} years old.".format("Alice", 25))

常用字串方法

text = "  Hello, World!  "

# 大小寫轉換
print(text.upper())       # "  HELLO, WORLD!  "
print(text.lower())       # "  hello, world!  "
print(text.capitalize())  # "  hello, world!  "
print(text.title())       # "  Hello, World!  "

# 去除空白
print(text.strip())   # "Hello, World!"
print(text.lstrip())  # "Hello, World!  "
print(text.rstrip())  # "  Hello, World!"

# 取代
print(text.replace("World", "Python"))  # "  Hello, Python!  "

# 分割
print("a,b,c".split(","))  # ['a', 'b', 'c']

# 查找
print("Hello".find("l"))   # 2(第一個 l 的位置)
print("Hello".count("l"))  # 2(l 出現的次數)

# 檢查
print("Hello".startswith("He"))  # True
print("Hello".endswith("lo"))    # True
print("123".isdigit())           # True
print("abc".isalpha())           # True

字串是不可變的

字串一旦建立就不能修改:

text = "Hello"
# text[0] = "J"  # TypeError!

# 要修改只能建立新字串
text = "J" + text[1:]
print(text)  # Jello