速戰速決 Python - python 數據類型: 字符串類型

速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd

速戰速決 Python - python 數據類型: 字符串類型

示例如下:

datatype/string.py

# python 字符串類型

# 定義字符串可以用 ""
a = "web"
# 定義字符串也可以用 ''
b = 'abcd'
# 字符串相加
c = a + b
print(c) # webabcd
# 取第 1 個字符
print(c[0]) # w
# 取最後一個字符
print(c[-1]) # d
# 取第 2 個字符到最後一個字符
print(c[1:]) # ebabcd
# 取第 1 個字符到倒數第 2 個字符(注:範圍不包含冒號右邊的值)
print(c[:-1]) #webabc
# 取第 2 個字符到第 4 個字符(注:範圍包含冒號左邊的值,但是不包含冒號右邊的值)
print(c[1:4]) # eba
# 取第 2 個字符到倒數第 3 個字符(注:範圍包含冒號左邊的值,但是不包含冒號右邊的值)
print(c[1:-2]) # ebab
# 像下面這樣修改字符串是不允許的,因爲字符串是不可變類型
# c[0] = "x"

# 通過 * 可以指定字符串重複的次數
print(c * 2) # webabcdwebabcd
# in 是否包含
print("ab" in c) # True
# not in 是否不包含
print("ab" not in c) # False
# 字符串是可遍歷的
for x in "abc":
    print(x)

# 轉義符 \ 的用法和其他語言差不多
# \x 就是將十六進制字符串轉爲對應的 ascii 字符
d = "\"\x77\x65\x62\""
print(d) # "web"
# 通過 r 取消轉義符的功能
e = r"\"\x77\x65\x62\""
print(e) # \"\x77\x65\x62\"
# \u 就是將 unicode 編碼轉爲對應的字符
print("\u738b") # 王

# 定義字符串時如果需要換行,可以像下面這樣通過 \n 實現
f = "111\n222\n333"
# 定義字符串時如果需要換行,也可以像下面這樣通過 '''''' 或 """""" 實現
g = '''111
222
333'''
print(f) # f 和 g 的輸出結果是一樣的
print(g) # f 和 g 的輸出結果是一樣的

# 通過 % 格式化字符串
h = "webabcd"
i = 40
j = "我是 %s, 今年 %d 歲" % (h, i)
print(j) # 我是 webabcd, 今年 40 歲
# 保留 2 位小數
print("%.2f" % 3.141592) # 3.14

# 通過 f 格式化字符串
k = f"我是 {h}, 今年 {i} 歲"
print(k) # 我是 webabcd, 今年 40 歲

# 通過 format() 格式化字符串
print('{}, {}'.format('web', 'abcd')) # web, abcd
print('{1}, {0}, {age}'.format('abcd', 'web', age=40)) # web, abcd, 40
print('{0:.2f}'.format(3.1415926)) # 3.14

速戰速決 Python https://github.com/webabcd/PythonSample
作者 webabcd

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章