Python 字串常用函式詳解

2021-10-07 21:16:06 字數 3497 閱讀 8630

作用:檢視sub是否在字串中,在的話返回索引,且只返回第一次匹配到的索引;若找不到則報錯;可以指定統計的範圍,[start,end) 左閉區間右開區間

str = "helloworldhhh"

print(str.index("h"))

print(str.index("hhh"))

# print(str.index("test")) 直接報語法錯誤:valueerror: substring not found

執行結果

0

10

作用:和index()一樣,只是找不到不會報錯,而是返回-1

str = "helloworldhhh"

print(str.index("h"))

print(str.index("hhh"))

print(str.index("test"))

執行結果

0

10-1

作用:統計子字串的數量;可以指定統計的範圍,[start,end) 左閉區間右開區間

str = "hello world !!! hhh"

print(str.count(" "))

print(str.count(" ", 5, 10))

執行結果

3

1

作用:將字串按照str分割成列表,如果引數 num 有指定值,則分隔 num+1 個子字串

str = "hello world !!! hhh"

print(str.split(" "))

print(str.split(" ", 1))

執行結果

['hello', 'world', '!!!', 'hhh']

['hello', 'world !!! hhh']

作用:移除字串頭尾指定的字串行chars,預設為空格

作用:移除字串頭部指定的字串行chars,預設為空格

作用:移除字串尾部指定的字串行chars,預設為空格

str = "   hello  every  "

print("1", str.strip(), "1")

print(str.lstrip(), "1")

print("1", str.rstrip())

str = "!!! cool !!!"

print(str.strip("!"))

執行結果

1 hello  every 1

hello every 1

1 hello every

cool

作用:把字串中的 old(舊字串) 替換成 new(新字串),count代表最多替換多少次,預設-1代表全部替換

str = "hello world !!! hhh"

print(str.replace(" ", "-"))

print(str.replace(" ", "-", 1))

執行結果

hello-world-!!!-hhh

hello-world !!! hhh

作用:將序列中的元素以指定的字元連線生成乙個新的字串

lists = ["1", "2", "3"]

tuples = ("1", "2", "3")

print("".join(lists))

print("".join(tuples))

print("-".join(lists))

執行結果

123

1231-2-3

作用:將字串都變成大寫字母

作用:將字串都變成小寫字母

str = "hello world !!! hhh"

print(str.upper())

print(str.lower())

執行結果

hello world !!! hhh

hello world !!! hhh

作用:檢查字串是否是以指定子字串開頭,如果是則返回 true,否則返回 false;可以指定統計的範圍,[start,end) 左閉區間右開區間

作用:相反這是結尾

str = "hello world !!! hhh"

print(str.startswith("h"))

print(str.startswith("hh"))

print(str.endswith("h"))

print(str.endswith("hhhh"))

執行結果

true

false

true

false

作用:檢查字串是否只由數字組成

str = "123134123"

print(str.isdigit())

執行結果

true

作用:檢查字串是否只由字母組成

str = "abc"

print(str.isalpha())

執行結果

true

作用:將字串按照行 ('\r', '\r\n', \n') 分隔

str = """

123456

789"""

print(str.splitlines())

with open("./file1.txt", encoding="utf-8") as f:

lists = f.read().splitlines()

print(lists)

執行結果

['', '123', '456', '789']

['name: jack ; salary: 12000', ' name :mike ; salary: 12300', 'name: luk ; salary: 10030', ' name :tim ; salary: 9000', 'name: john ; salary: 12000', 'name: lisa ; salary: 11000']

PYTHON字串常用函式

1.find and rfind 從左開始找 title find le 存在返回索引值,不存在 1 從右開始找 title find le 存在返回索引值,不存在 1 2.join 列表轉成字串 join list 3.split 字串轉成列表 ss,aa,cc split ss aa cc 4....

Python字串常用函式

capitalize 把字串的第乙個字元改為大寫 casefold 把整個字串的所有字元改為小寫 center width 將字串居中,並使用空格填充至長度width的新字串 count sub start end 返回sub在字串裡邊出現的次數,start和end引數表示範圍,可選。encode ...

Python 字串常用函式

函式 描述 返回值 str.capitalize 將字串的第乙個字元大寫 str.title 返回標題化的字串,即每個單詞的首字母都大寫 str.upper 全大寫str.lower 全小寫len str 返回字串的長度。用法與其他不同。str.count substring start end 統...