字串型別
字串 (String) 是 Python 中用來表示文字的資料型別。
建立字串
# 使用單引號或雙引號
name = 'Alice'
message = "Hello, World!"
# 多行字串使用三引號
poem = """玫瑰是紅色的,
紫羅蘭是藍色的,
Python 很棒,
我也是!"""
字串操作
text = "Python"
# 取得長度
print(len(text)) # 6
# 索引取值 (從 0 開始)
print(text[0]) # P
print(text[-1]) # n (負數從後面數)
# 切片
print(text[0:3]) # Pyt
print(text[2:]) # thon
字串方法
s = "hello world"
print(s.upper()) # HELLO WORLD
print(s.capitalize()) # Hello world
print(s.replace("world", "Python")) # hello Python
print(s.split(" ")) # ['hello', 'world']
字串格式化
name = "Alice"
age = 25
# f-string (推薦)
print(f"我是 {name},今年 {age} 歲")
# format 方法
print("我是 {},今年 {} 歲".format(name, age))
練習
建立一個字串變數儲存你的名字,然後用 f-string 輸出 "你好,{名字}!"
💻 程式碼編輯器
📤 執行結果
等待執行...