Python_從零開始學習_(27) 字串
阿新 • • 發佈:2018-11-09
1. 字串的定義
- 字串 就是 一串字元, 是程式語言中表示文字的資料型別
- 在 Python 中可以使用 一堆雙引號 "" 或者 一對單引號 ' ' 定義一個字串
- 雖然可以使用 \"" 或者 \'' 做字串的轉義, 但是在實際開發中:
- 如果字串內部需要使用 "", 可以使用 ' ' 定義字串
- 如果字串內部需要使用 ' ', 可以使用 " " 定義字串
- 可以使用 索引 獲取一個字串中 指定位置的字元 (索引計數從 0 開始)
- 也可以使用 for 迴圈遍歷
大多數程式語言都是用 雙引號"" 來定義字串 !!!
string = "hello world"
for c in string:
print(c)
2. 字串的常用操作
- 在 ipython3 中定義一個 字串, 例如: str = " "
- 輸入 xiaoming. 按下 Tap 鍵, ipython 會提示 字串 能夠使用的 方法
基本操作:
hello_str = "hello world" # 1. 統計字串長度 print(len(hello_str)) # 2. 統計某一個小字串的次數 print(hello_str.count('l')) # 3. 某一個子字串第一次出現的位置 print(hello_str.index('l'))
python 內建提供的方法很多, 使得在開發時, 能夠針對字串進行更加靈活的操作! 應對更多的開發需求!
方法分類 :
1) 判斷型別 - 9
2) 查詢和替換 - 7
3) 大小寫轉換 - 5
4) 文字對齊 - 3
5) 去除空白字元 - 3
6) 拆分和連結 - 5
2.1 常用判斷
# 1. 判斷空白字元 space_str = " " print(space_str.isspace()) # 2. 判斷字串中是否只包含數字 num_str = "1" # 2.1 都不能判斷小數 # num_str = "1.1" # 2.2 unicode 字串 # num_str = "\u00b2" # 2.3 中文 # num_str = "一千零一" print(num_str) print(num_str.isdecimal()) print(num_str.isdigit()) print(num_str.isnumeric())
2.2 查詢和替換
hello_str = "hello world"
# 1. 判斷是否以指定字串開始
print(hello_str.startswith("hello"))
# 2. 判斷是否以指定字串結束
print(hello_str.endswith("world"))
# 3. 查詢指定字串
# index 同樣可以查詢指定的字串在大字串在大字串中的索引
print(hello_str.find("llo"))
# index 如果指定的字串不存在, 會報錯
# find 如果指定的字串不存在, 會返回 -1
print(hello_str.find("adb"))
# 4. 替換字串
# replace方法執行完成之後, 會返回一個新的字串
# 注意: 不會修改原有字串的內容
print(hello_str.replace("world", "python"))
print(hello_str)
2.3 文字對齊
# 要求: 居中對齊以下內容
poem = ["連峰去天不盈尺,",
"枯鬆倒掛倚絕壁."]
for poem_str in poem:
# 居中對齊
print("|%s|"%poem_str.center(20, " "))
poem1 = ["連峰去天不盈尺,",
"枯鬆倒掛倚絕壁."]
for poem_str in poem1:
# 左對齊 右對齊rjust
print("|%s|"%poem_str.ljust(20, " "))
2.4 去除空白字元
poem = ["\t\n飛流直下三千尺",
"疑是銀河落九天"]
for poem_str in poem:
# 先使用strip方法去除字串中的空白字元
# 再使用center 方法居中
print("|%s|"%poem_str.strip().center(20, " "))
2.5 拆分和連線
poem = "\t\n飛流直下三千尺\t疑\n是銀河落九天"
print(poem)
# 1. 拆分字串, split() 裡面以什麼分隔成列表
poem_list =poem.split()
print(poem_list)
# 2. 合併字串
result = "".join(poem_list)
print(result)
3. 字串的切片
- 切片 方法適用於 字串, 列表 , 元組
- 切片 使用 索引值 來限定範圍, 從一個大的 字串 中 切出 小的 字串
- 列表 和 元組 都是 有序 的集合, 都能夠 通過索引值 獲取到對應的資料
- 字典 是一個 無序 的集合, 是使用 鍵值對 儲存資料
字串[開始索引:結束索引:步長]
注意 :
- 指定的區間屬於 左閉右開 型 [開始索引,結束索引] => 開始索引 => 範圍 => 結束索引
- 從 起始 位開始, 到 結束 位的前一位 結束 ( 不包含結束位本身 )
- 從頭開始, 開始索引 數字可以省略, 冒號不能省略
- 從末尾結束, 結束所以 數字可以申領, 冒號不能省略
- 步長預設為 1 , 如果連續切片, 數字和冒號都可以省略
poem = "大漠孤煙直,長河落日圓"
print(poem[2:4]) # 孤煙
print(poem[2:]) # 孤煙直,長河落日圓
print(poem[:-1]) # 大漠孤煙直,長河落日
print(poem[:]) # 大漠孤煙直,長河落日圓
print(poem[-1]) # 圓
print(poem[0::-1]) # 大
print(poem[-1::-1]) # 圓日落河長,直煙孤漠大
print(poem[::-1]) # 圓日落河長,直煙孤漠大
print(poem[::2]) # 大孤直長落圓
print(poem[::-2]) # 圓落長直孤大