目錄
1.字符串概念和注意事項
2.字符串內置函數
3.字符串的索引、切片和遍歷
4.字符串運算符
5.字符串常用方法
性質判斷
開頭結尾判斷
是否存在某個子串
大小寫等格式轉化
子串替換
刪除兩端空白字符
格式化字符串
分割與合并
6.字符串模板
7.exec 函數
8.字符串加密和解密
1.字符串概念和注意事項
s1 = "abc"
s2 = "abc"
print(id(s1))
print(id(s1) == id(s2)) # True
s = "abc"
s[2] = 'x'
報錯提示
TypeError: 'str' object does not support item assignment
解釋:s = "abc"表示生成了一個s變量,s = "abc"語句后,在內存中開辟了一塊地址,專門用來存放"abc"這個字符串,且s當前所代表的內存地址是"abc"的地址。字符串對象不可變指的是"abc"是不可變的,s[0]='x'操作就是試圖將存放在內存中的"abc"的第一個元素改為'x',這是不允許的。
如果你想要修改字符串中的某個字符,你必須創建一個新的字符串。例如,你可以通過切片(slicing)和字符串連接(concatenation)等來實現這一點
s = "abc"
s2 = s[:2] + 'x'
print(s2) # abx
也可以對變量重新賦值,本質是對變量s更換了一個地址
s = "abc"
print(id(s))
s = "abx"
print(id(s))
2.字符串內置函數
常用的有len獲取長度,max獲取最大字符等
s = "ac1"
print(len(s)) # 返回字符串的長度,3
print(max(s)) # 返回字符串中“最大”的字符,c
print(min(s)) # 返回字符串中“最小”的字符,1
3.字符串的索引、切片和遍歷
s[0: len(s)] = ss[: 4] = s[0: 4]
s[2: ] = s[2: len(s)]
s[ : ] = ss[ : -1] = s[0: -1] = s[0 : -1 + len(s)]
s[-2 : ] = s[-2 : len(s)] = s[-2 + len(s) : len(s)]
s[-5 : -2] = s[-5 + len(s) : -2 + len(s)]s[1 : y] = s[1 : len(s)] # 如果 y >= len(s)的話
s[2 : 1] = '' # 空串
s[2 : 2] = '' # 空串
for ch in "abcd":print(ch, end=" ")
# a b c d
4.字符串運算符
print('ab' + 'cd') # abcd
print('ab' * 2) # abab
print(2 * 'ab') # abab
print('He' in "He and I") # True
print('he' in "He and I") # False
print('he' not in "he ta") # False
print("abc" < "abcd") # True
print("abd" < "a1c") # False
print("Jane" < "Jacksandffs") # False
5.字符串常用方法
性質判斷
返回值為布爾變量 bool
s.isalnum(),如果字符串中的字符只有數字或者字母,則返回 True
s.isalpha(),如果字符串中的字符只有字母,則返回 True
s.isdigit(),如果字符串中的字符只有數字,則返回 True
s.isdecimal(),如果字符是十進制數字,則返回 True
print('234 '.isdigit()) # False
print('234'.isdigit()) # True
s.isidentifier(),如果這個字符串滿足 python 標識符的要求,則返回 True
print('_radius'.isidentifier()) # True
print('2radius'.isidentifier()) # False
print('2ad '.islower()) # True
print('2Ad '.islower()) # False
print('2AD '.isupper()) # True
print('2 '.isspace()) # False
print(' '.isspace()) # True
開頭結尾判斷
print('radius'.endswith("usa")) # False
print('radius'.startswith("ra")) # True
是否存在某個子串
s.find(s1, starti, endi),返回字符串 s 中第一次出現子串 s1 時,此時 s1 第一個字符的下標;找不到返回-1
s.rfind(s1, starti, endi),返回字符串 s 中最后一次出現子串 s1 時,此時 s1 第一個字符的下標;找不到返回-1
print("mynameisname".find('name')) # 2
print("mynameisname".rfind('name')) # 8
print("xxxxabc".count('xx')) # 2
print("xxxxabcxxx".count('xx')) # 3data = "hello world"
if data.find("age") == -1:print("not find")
else:print("exist")
大小寫等格式轉化
s.capitalize(),返回只大寫第一個字符的字符串
s.lower(),返回全是小寫的字符串
s.upper(),返回全是大寫的字符串
s.title(),返回只將每個單詞首字母大寫的字符串
s.swapcase(),返回大小寫互換的字符串,就是大寫字母變成小寫,小寫字母變大寫
print("the happy of python".title()) # The Happy Of Python
子串替換
s = "abcd"
s1 = s.replace("ab", "xyz")
print(s) # abcd
print(s1) # xyzcd
技巧:替換為空字符串表示刪除
s = "abcdab"
s1 = s.replace("ab", "")
print(s) # abcd
print(s1) # cd
刪除兩端空白字符
s = " x y z "
s1 = s.strip()
print(f"({s1})") # (x y z)
格式化字符串
s = "abcd"
s1 = s.center(10)
print(f"({s1})") # ( abcd )
分割與合并
mystr = "A1021879743 # 1021879743 # www.1021879743@qq.com"
mylist = mystr.split(" # ") # 按照 # 切割,返回列表
print(mylist) # ['A1021879743', '1021879743', 'www.1021879743@qq.com']
mystr = "88548 n 小姐 女 22 162"
mylist = mystr.split(" ", 2) # 按空格切割,切割 2 次就停止
print(mylist) # ['88548', 'n', '小姐 女 22 162']
mystr = """88548
n 小姐 女
22 162"""
mylist = mystr.splitlines() # 根據換行符切割
print(mylist) # ['88548 ', 'n 小姐 女', '22 162']
字符串partition()函數
partition()方法用來根據指定的分隔符將字符串進行分割。
如果字符串包含指定的分隔符,則返回一個3元的元組,第一個為分隔符左邊的子串,第二個為分隔符本身,第三個為分隔符右邊的子串。
如果未找到separator參數,字符串本身和兩個空字符串
data = "name=bob;age=10"
ret = data.partition(";")
print(ret) # ('name=bob', ';', 'age=10')data = "name=bob"
ret = data.partition(";")
print(ret) # ('name=bob', '', '')
字符串合并:join 函數
將列表等可迭代對象按特定符號拼接成字符串
mystr = "這是一個國家級機密"
lst = list(mystr)
print(lst) # ['這', '是', '一', '個', '國', '家', '級', '機', '密']newstr = "#".join(mystr)
print(newstr) # 這#是#一#個#國#家#級#機#密
6.字符串模板
from string import Template # string 模塊導入 Template# print(type(Template)) # <class 'string._TemplateMetaclass'># 搭建模板
mystr = Template("hi, $name 你是 $baby")# 模板使用
print(mystr.substitute(name="羅翔", baby="老師"))
print(mystr.substitute(name="張三", baby="學生"))'''
hi, 羅翔 你是 老師
hi, 張三 你是 學生
'''
7.exec 函數
作用:將字符串當做命令行語句來執行
import os
mystr = 'os.system("notepad")'
exec(mystr)
8.字符串加密和解密
加密:按指定規律將字符串的每一個字符變為另一個字符。
解密:將加密后的內容指定規律還原原內容。
第一種:自定義加碼:str.maketrans(old, new)
mystr = "hello python 我,我,你"
table = str.maketrans("我你 x", "他它 y") # 我替換成他,你替換成它,x 替換成 y
print(mystr) # hello python 我,我,你
print(mystr.translate(table)) # hello python 他,他,它
realStr = "這是一個國家級機密"
key = 5faceStr = [chr(ord(x) + key) for x in list(realStr)]
print(faceStr) # ['連', '昴', '丅', '丯', '圂', '宻', '緯', '朿', '寋']correctStrList = [chr(ord(x) - key) for x in list(faceStr)]
correctStr = "".join(correctStrList)
print(correctStr)
這些是最基礎最簡單的加密解密,日常使用足夠。
end