2026 Mar. 08 講師 藍少君
"Hello, World"
print("Hello, World")
用 單引號(' ') 或 雙引號(" ") 夾注文字。
' '
" "
合法的字串:
str1 = "a valid string" str2 = 'a valid string' str3 = "s" # a string with a single character str4 = ' ' # a string with one "space" character str5 = "" # an empty string
在程式內直接寫出字串的內容,這樣的字串表示被稱為 string literal。
h = "Hello" w = "World" hw = h + ", " + w # 字串串接 print(hw) # Hello, World
hw = "Hello World" h, w = hw.split() # 用空白分割 print(h) # Hello print(w) # World
# 如果輸入 1 number_str = input() # number_str = "1" number = int(number_str) # number = 1
'a'
'1'
','
"OuO"
['O', 'u', 'O']
想要表示換行字元 => 輸入 \n。 (常見)
\n
str1 = "abc\n123" print(str1) # abc # 123
Fun Fact: print() 預設會在輸出完字串後,補一個換行字元 '\n'。
print()
'\n'
想要在單(雙)引號字串中表示單(雙)引號 => 輸入 \'(\")。
\'
\"
錯誤寫法:
str1 = "He said "Hello" to me."
正確寫法:
str1 = "He said \"Hello\" to me."
想要表示反斜線 => 輸入 \\。
\\
str1 = "I'm not going to make a \new line." # I'm not going to make a # ew line str2 = "I'm not going to make a \\new line." # I'm not going to make a \new line
'0'
'9'
'A'
'Z'
'z'
ASCII 編碼表: https://en.wikipedia.org/wiki/ASCII#Table_of_codes
在 Python 中可以使用 ord() 來獲得某個字元的 ASCII 編碼;使用 chr() 來獲得某個 ASCII 編碼對應的字元。
ord()
chr()
print(ord('0')) # 48 print(chr(48)) # '0'
透過操作 ASCII 編碼,將字母小寫轉大寫:
alphabet = 'x' print(chr(ord(alphabet) - ord('a') + ord('A'))) # 'X'
print("你好") print("これもOKです") print("")
1:
"1":
.replace()
.split()
1 + "1" = ?
TypeError: unsupported operand type(s) for +: 'int' and 'str'
不支援將整數(int)及字串(str)相加。
print("string")
print(1)
print("1")
"1"
str(1)
可以參考 pypy 的實做更深入理解: pypy/module/__builtin__/app_io.py#L96 "類似" str(1) 的說法,是因為在我們使用的 CPython 實做中,並不會有顯式的 str(1) 呼叫。
str1 = "string"
str2 = input()
str3 = str(1.1)
"He" + "llo"
"Hello"
"Ha" * 3
"HaHaHa"
'A' > 'a'
False
'a' > '?'
True
'A' <= c <= 'Z'
'aca' > 'abz'
'aaaa' > 'aaa'
hw = "Hello, World" # 可以透過 index 來得到單一字元 print(hw[0]) # H # 可以使用 slice 相關的功能 print(hw[0:5], hw[11:6:-1]) # Hello dlroW
hw = "Hello, World" # 可以使用 for 來遍歷 for c in hw: print(c, end='_') # H_e_l_l_o_,_ _W_o_r_l_d_ # 可以透過 len() 取得長度 print(len(hw)) # 12
string 和 list 不同的是,string 在 Python 中是不可變的。
h = "Hollo" h[1] = 'e'
TypeError: 'str' object does not support item assignment
不可變指的是在 string 的實做中,不存在有任何能改變其內部結構的功能。 有興趣可以到網路上查詢相關設計的原因。
h = "Hollo" h = h[:1] + 'e' + h[2:] # "Hello"
雖然最後達到了修改的效果,但背後運作並不是把原字串的第二個字改掉,而是創建 "H"、"e"、"llo" 三個字串,最後串接起來。
"H"
"e"
"llo"
將 原字串(放在點點前面) 依 提供的分隔符號(另一個字串,放在小括號內) 進行分割,回傳一個字串的 list,表示所有被分開的段落。
str1 = "A, B, C" outcome = str1.split(", ") print(outcome) # ["A", "B", "C"]
若不指定分隔字串,預設會用空白 ' ' 當作分隔字串。
Judge 中經常會有 第一行為兩個數字 n, m,用空白分隔,... 相關的輸入規格,這時就會用到 .split()。
judge_input = input() # "1 2" split_outcome = judge_input.split() # ["1", "2"] n, m = split_outcome # unpack, n = "1", m = "2" n, m = int(n), int(m)
精簡版本: n, m = map(int, input().split())
n, m = map(int, input().split())
將 原字串(放在點點前面) 內 指定的 pattern (另一個字串,放在小括號內的第一個參數) 替換成另一個 pattern (另一個字串,放在小括號內的第二個參數),回傳替換後的字串。
text = "I like banana" new_text = text.replace("banana", "apple") print(text) # I like banana print(new_text) # I like apple
.strip()
將 原字串(放在點點前面) 字串最前方連續、最後方連續指定的字元們 (另一個字串,放在小括號內) 刪除,回傳處理後的字串。
str1 = " 123 " strip_str1 = str1.strip() # "123" str2 = "www.example.com" strip_str2 = str2.strip("w.com") # "example"
若不指定 strip 字元,預設為 ' '。
.join()
.find()
.lower()
.upper()
用 三個雙引號(""") 開始一個多行字串,可以用來撰寫有結構文字,也是 Python 內多行註解的標準方法。
"""
str1 = """ Never gonna give you up Never gonna let you down Never gonna run around and desert you """ print(str1)
""" for i in range(10): print("foo") """ for i in range(10): print("bar")
f
answer1, answer2 = 1, 2 # Without f-string print("The answer is: (" + str(answer1) + ", " + str(answer2) + ")") # With f-string: print(f"The answer is: ({answer1}, {answer2})")
{}
w, h = 50, 1.7 print(f"BMI is: {w / (h ** 2)}")
padding and alignment:
print(f"|{'姓名':^10}|{'座號':^10}|") # | 姓名 | 座號 | print(f"|{'姓名':*<4}|{'座號':*<4}|") # |姓名**|座號**| print(f"|{'姓名':->8}|{'座號':->8}|") # |------姓名|------座號|
小數進位:
pi = 3.1415926 print(f"pi: {pi:.2f}") # 3.14 print(f"pi: {pi:.3f}") # 3.142
Debug:
outcome = "haha" print(f"{outcome=}") # outcome='haha'