立即學習:https://edu.csdn.net/course/play/24797/282156?utm_source=blogtoedu
★ 本節目標
- 轉義字符
- 字符串格式化 (重點、難點)
- 調用函數(方法)操作字符串(重點)
★ 轉義字符
如果字符串本身包含反斜線,則需要使用\\表示,其中\\就是轉義字符。
s = 'a\tb\tc'
print(s)
s2 = 'a\nb\nc'
print(s2)
★ 字符串格式化
使用%加轉換說明符的方式執行字符串格式化,Python支持如下所示轉換說明符。
s = '我愛%s'
print(s % 'Python')
#s2先轉成str,d代表十進制整數
s2 = '我最愛的圖書是%s,價格是%d'
print(s2 % ('瘋狂Python講義' , 128))
price = 128
s3 = '價格是%d , 八進制爲:%o , 十六進制爲:%x , 字符串形式爲:%r'
print(s % (price , price ,price , price) )
★ 序列相關的方法
- 字符串本質就是由多個字符組成,字符串的本質就是不可變序列,因此序列相關的方法:
- 基於索引的計算
- in運算
- len()函數
- min()、max()函數
s = 'fkjava.org'
#根據下標訪問
print(s[3])
#指定開始、結束
print(s[2 : 4])
#指定開始、結束、步長
print(s[2 : 6 : 3])
print('org' in s) # True
print('ork' in s) # False
print('s字符串的長度爲:' , len(s))
print(max(s)) # v
print(min(s)) # .
#字符串的方法
print(s.upper()) # FKJAVA.ORG
print(s.title()) # Fkjava.Org
print(s.lower()) # fkjava.org
#dir可以查看某個類的所有方法
print(s.islower())
★ 大小寫相關的方法
- title():將每個單詞首字母改爲大寫。
- lower():將整個字符串改爲小寫。
- upper():將整個字符串改爲大寫。
dir()可以查看某個類的所有方法。
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__'
, '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__','__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isascii', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']
#使用help命令可以查看某個方法的具體用法
>>> help(str.islower)
Help on method_descriptor:
islower(self, /)
Return True if the string is a lowercase string, False otherwise.
A string is lowercase if all cased characters in the string are lowercase and
there is at least one cased character in the string.
★ 刪除空白
- strip():刪除字符串前後的空白
- lstrip():刪除字符串前面(左邊)的空白。
- rstrip():刪除字符串後面(右邊)的空白。
s = ' fkjava.org '
print(s.strip())
print(s.lstrip())
print(s.rstrip())
★ 查找、替換相關方法
- startswith():判斷字符串是否以指定子串開頭。
- endswith():判斷字符串是否以指定子串結尾。
- find():查找指定子串在字符串中的出現位置,如果沒有找到指定子串,則返回-1。
- index():查找指定子串在字符串中的出現位置,如果沒有找到指定子串,則引發ValueError錯誤。
- replace():使用指定子串替換字符串中的目標子串。
- translate():使用指定的翻譯映射表對字符串執行替換。
s = 'fkjava.org'
print(s.find("ava")) #3
print(s.find("aja")) #-1
★ 分割、連接
- split():將字符串按指定分隔符分割成多個短語。
- join():將多個短語連綴成字符串。
s = 'www.fkjava.org'
print(s.split('.')) #['www', 'fkjava', 'org']
print('='.join(s.split("."))) #www=fkjava=org
★ 本節小結
- 轉義字符
- 字符串格式化
- 字符串相關函數和方法