⼀對引號字符串或三引號字符串,若是須要用到引號則須要在前面增長"/"轉義字符,三引號形式的字符串⽀持換⾏。php
a = 'i' b = "also" c = '''like''' d = """python""" e = 'i\'am vincent' print(a) print(b) print(c) print(d) print(e)
控制檯顯示結果爲<class 'str'>,即數據類型爲str(字符串)。java
在Python中,使⽤ input() 接收⽤戶輸⼊。python
name = input('請輸⼊你的名字:') print('你的名字是%s' % name) print(type(name)) password = input('請輸⼊你的密碼:') print(f'你的密碼是{password}') print(type(password))
切⽚是指對操做的對象截取其中⼀部分的操做。字符串、列表、元組都⽀持切⽚操做。c++
語法:序列[開始位置下標:結束位置下標:步⻓]
git
- 不包含結束位置下標對應的數據, 正負整數都可
- 步⻓是選取間隔,正負整數都可,默認步⻓爲1。
name = "abcdef" print(name[2:4:1]) # cd print(name[2:4]) # cd print(name[:4]) # abcd print(name[1:]) # bcdef print(name[:]) # abcdef print(name[::2]) # ace print(name[:-1]) # abcde, 負1表示倒數第⼀個數據 print(name[-3:-1]) # de print(name[::-1]) # fedcba
查找⽅法便是查找⼦串在字符串中的位置或出現的次數api
語法:字符串序列.find(⼦串, 開始位置下標, 結束位置下標)
函數
開始和結束位置下標能夠省略,表示在整個字符串序列中查找。spa
mystr = 'i like python and java and c++ and php' print(mystr.find('and')) # 14 print(mystr.find('and', 15, 30)) # 23 print(mystr.find('amd')) # -1
語法:字符串序列.index(⼦串, 開始位置下標, 結束位置下標)
code
開始和結束位置下標能夠省略,表示在整個字符串序列中查找對象
mystr = 'i like python and java and c++ and php' print(mystr.index('and')) # 14 print(mystr.index('and', 15, 30)) # 23 print(mystr.index('amd')) # -1
語法:字符串序列.count(⼦串, 開始位置下標, 結束位置下標)
開始和結束位置下標能夠省略,表示在整個字符串序列中查找。
mystr = 'i like python and java and c++ and php' print(mystr.count('and')) # 3 print(mystr.count('and', 15, 30)) # 1 print(mystr.count('amd')) # 0
修改字符串指的就是經過函數的形式修改字符串中的數據
語法:字符串序列.replace(舊⼦串, 新⼦串, 替換次數)
mystr = 'i like python and java and c++ and php' print(mystr.replace('and', '和')) print(mystr.replace('and', '和', 5)) print(mystr) 輸出結果爲: i like python 和 java 和 c++ 和 php i like python 和 java 和 c++ 和 php i like python and java and c++ and php
數據按照是否能直接修改分爲可變類型和不可變類型兩種。字符串類型的數據修改的時候 不能改變原有字符串,屬於不能直接修改數據的類型便是不可變類型
語法:字符串序列.split(分割字符, num)
mystr = 'i like python and java and c++ and php' print(mystr.split('and')) print(mystr.split('and', 2)) print(mystr.split(' ')) print(mystr) 輸出結果爲: ['i like python ', ' java ', ' c++ ', ' php'] ['i like python ', ' java ', ' c++ and php'] ['i', 'like', 'python', 'and', 'java', 'and', 'c++', 'and', 'php'] i like python and java and c++ and php
語法:字符或⼦串.join(多字符串組成的序列)
mylist = ['python', 'java', 'c++', 'php'] print(' '.join(mylist)) print('...'.join(mylist)) print(mylist) 輸出結果爲: python java c++ php python...java...c++...php ['python', 'java', 'c++', 'php']
語法:字符串序列.ljust(⻓度, 填充字符)
判斷便是判斷真假,返回的結果是布爾型數據類型:True 或 False
語法:字符串序列.startswith(⼦串, 開始位置下標, 結束位置下標)
mystr = 'i like python and java and c++ and php' print(mystr.startswith('i')) # True print(mystr.startswith('i like')) # True print(mystr.startswith('he')) # False