在Python中,字符串是不可變序列類型,提供了豐富的內置方法。以下是常用的字符串操作方法及示例:
1. 大小寫轉換
-
lower() 轉小寫
-
upper() 轉大寫
-
capitalize()?首字母大寫
-
title()?每個單詞首字母大寫
-
swapcase()?大小寫互換?
print("HELLO".lower()) # hello
print("hello".upper()) # HELLO
print("python".capitalize()) # Python
print("hello world".title()) # Hello World
print("PyThon".swapcase()) # pYtHON
2. 查找與替換
-
find(sub, start, end):查找子串,返回索引,找不到返回-1,start 和 end 為可選參數
-
rfind(sub):從右側查找子串?
-
index(sub):類似find(),但找不到時會報錯
- replace(old, new, count):替換子串,count指定替換次數為可選參數
print("apple".find("p")) #1
print("apple".find("p",3)) # -1print("apple".rfind("p")) # 2
print("apple".index("p")) # 1 找不到報錯
print("banana".replace("a", "o", 2)) # bonona
3.?字符串判斷
-
startswith(prefix, start, end):是否以指定前綴開頭,start 和 end 為可選參數
-
endswith(suffix):是否以指定后綴結尾?
-
isalpha():是否全為字母?
-
isdigit():是否全為數字
-
isalnum():是否全為字母或數字
-
isspace():是否全為空白符
print("hello".startswith("he")) # True
print("hello".endswith("lo")) # True
print("123ABC".isdigit()) # False
print("123".isdigit()) # True
print("123ABC".isalnum()) # True
print("\t \n".isspace()) # True
4.?分割與連接
-
split(sep,maxsplit) :按分隔符分割為列表
-
rsplit(sep,maxsplit):?從右側分割字符
-
splitlines():按行分割
-
join(iterable):連接字符串序列
print("a,b,c".split(",",1)) #['a', 'b,c']
print("a,b,c".rsplit(",",1)) #['a,b', 'c']
print("line1\nline2".splitlines()) # ['line1', 'line2']
print("!".join(["a", "b", "c"]) ) #a!b!c
5.?空白處理
-
strip():移除兩側空白或指定字符
-
lstrip():移除左側空白或指定字符
-
rstrip():移除右側空白或指定字符
print(" hello ".strip()) # hello
print("xxxworld".lstrip("xxx")) # world
print("helloxxx".rstrip("xxx")) # hello
6.?對齊與填充
-
center(width):居中填充
-
ljust(width):左對齊填充
-
rjust(width):右對齊填充
-
zfill(width):左側用0填充
print("center".center(8,'0')) # 0center0
print("hello".ljust(8,'0')) # hello000
print("hello".rjust(8,'0')) #000hello
print("hello".zfill(10)) #00000hello
7.?格式化
-
f 格式化字符串
-
format() 格式化表達式
name = "Alice"
print(f"Hello, {name}!") #Hello, Alice!
print("{0} + {1} = {2}".format(1, 2, 3)) #1 + 2 = 3
8.?其他操作
-
len(str):獲取字符串長度
-
in:檢查字符串存在某個字符
-
not in:檢查字符串不存在某個字符
-
count(sub,start,end):統計子串出現次數
-
encode(encoding="utf-8"):編碼為字節
print(len("hello world")) # 11
print("a" in("apple")) # True
print("o" not in("apple")) #True
print("aaabbbccc".count("a",0,2)) #2
print("你好".encode(encoding="utf-8")) # b'\xe4\xbd\xa0\xe5\xa5\xbd'
掌握這些方法可高效處理文本數據,注意字符串不可變性:所有操作均返回新字符串,原字符串不變。