1. 程式人生 > >python的字串總結

python的字串總結

1、

查詢和替換 - 7

| 方法 | 說明 | | --- | --- | | string.startswith(str) | 檢查字串是否是以 str 開頭,是則返回 True | | string.endswith(str) | 檢查字串是否是以 str 結束,是則返回 True | | string.find(str, start=0, end=len(string)) | 檢測 str 是否包含在 string 中,如果 start 和 end 指定範圍,則檢查是否包含在指定範圍內,如果是返回開始的索引值,否則返回 `-1` | | string.rfind(str, start=0, end=len(string)) | 類似於 find(),不過是從右邊開始查詢 |  | string.index(str, start=0, end=len(string)) | 跟 find() 方法類似,不過如果 str 不在 string 會報錯 | | string.rindex(str, start=0, end=len(string)) | 類似於 index(),不過是從右邊開始 | | string.replace(old_str, new_str, num=string.count(old)) | 把 string 中的 old_str 替換成 new_str,如果 num 指定,則替換不超過 num 次 |

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("abc"))

# 4. 替換字串
# replace方法執行完成之後,會返回一個新的字串
# 注意:不會修改原有字串的內容
print(hello_str.replace("world", "python"))

print(hello_str)

2、

大小寫轉換 - 5

| 方法 | 說明 | | --- | --- | | string.capitalize() | 把字串的第一個字元大寫 | | string.title() | 把字串的每個單詞首字母大寫 | | string.lower() | 轉換 string 中所有大寫字元為小寫 | | string.upper() | 轉換 string 中的小寫字母為大寫 | | string.swapcase() | 翻轉 string 中的大小寫 |

#### 4) 文字對齊 - 3

| 方法 | 說明 | | --- | --- | | string.ljust(width) | 返回一個原字串左對齊,並使用空格填充至長度 width 的新字串 | | string.rjust(width) | 返回一個原字串右對齊,並使用空格填充至長度 width 的新字串 | | string.center(width) | 返回一個原字串居中,並使用空格填充至長度 width 的新字串 |

# 假設:以下內容是從網路上抓取的
# 要求:順序並且居中對齊輸出以下內容
poem = ["\t\n登鸛雀樓",
         "王之渙",
         "白日依山盡\t\n",
         "黃河入海流",
         "欲窮千里目",
         "更上一層樓"]

for poem_str in poem:

    # 先使用strip方法去除字串中的空白字元
    # 再使用center方法居中顯示文字
    print("|%s|" % poem_str.strip().center(10, " "))

去除空白字元 - 3

| 方法 | 說明 | | --- | --- | | string.lstrip() | 截掉 string 左邊(開始)的空白字元 | | string.rstrip() | 截掉 string 右邊(末尾)的空白字元 | | string.strip() | 截掉 string 左右兩邊的空白字元 |

#### 6) 拆分和連線 - 5

| 方法 | 說明 | | --- | --- | | string.partition(str) | 把字串 string 分成一個 3 元素的元組 (str前面, str, str後面) | | string.rpartition(str) | 類似於 partition() 方法,不過是從右邊開始查詢 | | string.split(str="", num) | 以 str 為分隔符拆分 string,如果 num 有指定值,則僅分隔 num + 1 個子字串,str 預設包含 '\r', '\t', '\n' 和空格 | | string.splitlines() | 按照行('\r', '\n', '\r\n')分隔,返回一個包含各行作為元素的列表 | | string.join(seq) | 以 string 作為分隔符,將 seq 中所有的元素(的字串表示)合併為一個新的字串 |

# 假設:以下內容是從網路上抓取的
# 要求:
# 1. 將字串中的空白字元全部去掉
# 2. 再使用 " " 作為分隔符,拼接成一個整齊的字串
poem_str = "登鸛雀樓\t 王之渙 \t 白日依山盡 \t \n 黃河入海流 \t\t 欲窮千里目 \t\t\n更上一層樓"

print(poem_str)

# 1. 拆分字串
poem_list = poem_str.split()
print(poem_list)

# 2. 合併字串
result = " ".join(poem_list)
print(result)

7、