字符串
字符串 是Python中的 不可變 數(shù)據(jù)類型
1.字符串相關(guān)處理方法
- 大小寫轉(zhuǎn)換
# 大小寫轉(zhuǎn)換
s1='HelloWorld'
new_s2=s1.lower()
print(s1,new_s2)
new_s3=s1.upper()
print(new_s3)
結(jié)果:
D:\Python_Home\venv\Scripts\python.exe D:\Python_Home\chap6\示例6-1字符串的相關(guān)處理方法1.py
HelloWorld helloworld
HELLOWORLD
- 字符串的分隔
e_mail='2624137649@qq.com'
lst=e_mail.split('@')
print('郵箱名:',lst[0],'郵箱服務(wù)器域名:',lst[1])
結(jié)果:
郵箱名: 2624137649 郵箱服務(wù)器域名: qq.com
- 判斷前綴和后綴
s1='HelloWorld'
print(s1.startswith('H')) #True
print(s1.startswith('P')) #False
print('demo.py'.endswith('.py'))
print('demo.text'.endswith('.text'))
結(jié)果:
True
False
True
True
- 字符串的替換
s='HelloWorld'
#字符串的替換
new_s=s.replace('o','你好',1) #最后一個參數(shù)是替換次數(shù),默認是全部替換
print(new_s)
結(jié)果:
Hell你好World
- 字符串在指定的寬度范圍內(nèi)居中
s='HelloWorld'
print(s.center(20))
print(s.center(20,'*'))
結(jié)果:
HelloWorld
*****HelloWorld*****
注:第一個HelloWorld 左右兩邊都有空格的
- 去掉字符串左右的空格
s=' Hellow world '
print(s.strip())
print(s.lstrip()) #去掉字符串左側(cè)的空格
print(s.rstrip()) #去掉字符串右側(cè)的空格
結(jié)果:
Hellow world
Hellow world
Hellow world
- #去掉指定的字符
s3='dl-Helloworld'
print(s3.strip('ld')) #與順序無關(guān) -Hellowor
print(s3.lstrip('ld')) # -Helloworld
print(s3.rstrip('dl')) # dl-Hellowor
結(jié)果:
-Hellowor
-Helloworld
dl-Hellowor
2.格式化字符串
- 使用占位符進行格式化
name='馬冬梅'
age=18
score=98.5
print('姓名:%s,年齡:%d,成績:%f' % (name,age,score))
結(jié)果:
姓名:馬冬梅,年齡:18,成績:98.500000
此時成績后面有很多小數(shù)點 00000怎么辦?
那我們就精確一下位數(shù),更改代碼:
print('姓名:%s,年齡:%d,成績:%.1f' % (name,age,score))
結(jié)果:
姓名:馬冬梅,年齡:18,成績:98.5
- f-string
name='馬冬梅'
age=18
score=98.5
print(f'姓名:{name},年齡:{age},成績:{score}')
結(jié)果:
姓名:馬冬梅,年齡:18,成績:98.5
- 使用字符串的 format 方法 #0、1、2 相當于索引
name='馬冬梅'
age=18
score=98.5
print('姓名:{0},年齡:{1},成績:{2}'.format(name,age,score))
print('姓名:{2},年齡:{0},成績:{1}'.format(age,score,name))
結(jié)果:
姓名:馬冬梅,年齡:18,成績:98.5
姓名:馬冬梅,年齡:18,成績:98.5
3.字符串的編碼和解碼
將str類型轉(zhuǎn)換成 bytes 類型,需要用到字符串的 encode()方法
str.encode(encoding=‘utf-8’,errors=‘strict/ignore/replace’)
bytes.decode(encoding=‘utf-8’,errors=‘strict/ignore/replace’)
注:errors=‘strict/ignore/replace’ 里面是 分別是三種編碼和解碼出錯時,出現(xiàn)的三種反應(yīng)的模式
- 編碼:
s='偉大的中國夢'
#編碼 str->bytes
scode=s.encode(errors='replace') #默認是utf-8,因為 utf-8中文占3個字節(jié)
print(scode)
結(jié)果:
b'\xe4\xbc\x9f\xe5\xa4\xa7\xe7\x9a\x84\xe4\xb8\xad\xe5\x9b\xbd\xe6\xa2\xa6'
gbk:
scode_gbk=s.encode('gbk',errors='replace')
print(scode_gbk)
結(jié)果:
b'\xce\xb0\xb4\xf3\xb5\xc4\xd6\xd0\xb9\xfa\xc3\xce'
-
編碼中的出錯問題:
(這里我們想辦法去找一個圖標)
(1).replace
s2='耶??'
scode_error=s2.encode('gbk',errors='replace') #strict
print(scode_error)
結(jié)果:
b'\xd2\xae?'
在 replace 模式下這種圖標編程一種: 問號
(2). ignore (忽略)
s2='耶??'
scode_error=s2.encode('gbk',errors='ignore') #strict
print(scode_error)
結(jié)果:
b'\xd2\xae'
它就忽略了
(3). strict
s2='耶??'
scode_error=s2.encode('gbk',errors='strict') #strict
print(scode_error)
結(jié)果:
Traceback (most recent call last):
File "D:\Python_Home\chap6\示例6-5字符串的編碼和解碼.py", line 17, in <module>
scode_error=s2.encode('gbk',errors='strict') #strict
^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
UnicodeEncodeError: 'gbk' codec can't encode character '\U0001f92e' in position 1: illegal multibyte sequence
報錯了
- 解碼 bytes->str
print(bytes.decode(scode_gbk,'gbk'))
print(bytes.decode(scode,'utf-8'))
結(jié)果:
偉大的中國夢
偉大的中國夢
4.數(shù)據(jù)的驗證
- 判斷是否為數(shù)字
print('123'.isdigit()) #True
print('一二三'.isdigit()) #False
print('02j223'.isdigit()) #False
- 所有字符都是數(shù)字
print('1234'.isnumeric()) #True
print('一二三'.isnumeric()) #True
print('02j223'.isnumeric()) #False
print('壹貳叁'.isnumeric()) #True
中文的 "一二三"和 “壹貳叁” 都是可以識別的
- 所有字符都是字母(包含中文字符)
print('hello你好'.isalpha()) #True
print('hello你好123'.isalpha()) #False
print('hello你好一二三'.isalpha()) #True
print('hello你好壹貳叁'.isalpha()) #True
- 所有字符都是數(shù)字或字母
print('hello你好'.isalnum()) #True
print('hello你好123'.isalnum()) #False
print('hello你好一二三'.isalnum()) #True
print('hello你好壹貳叁'.isalnum()) #True
- 所有字符都是首字母大寫
print('Hello'.istitle()) #True
print('HelloWorld'.istitle()) #False
print('Helloworld'.istitle()) #True
print('Hello World'.istitle()) #True
print('Hello world'.istitle()) #False
- 判斷是否都是空白字符
print('\t'.isspace()) #True
print(' '.isspace()) #True
print('\n'.isspace()) #True
字符串的拼接
- 使用+號
s1='hello'
s2='world'
print(s1+s2)
- 使用字符串的 join()方法
s1='hello'
s2='world'
print(''.join([s1,s2]))
print('*'.join(['hello','world','python','java','php']))
結(jié)果:文章來源:http://www.zghlxwxcb.cn/news/detail-761277.html
helloworld
hello*world*python*java*php
- 直接拼接
print('hellow''world')
- 使用格式化字符串進行拼接
s1='hello'
s2='world'
print('%s%s' % (s1,s2))
print(f'{s1}{s2}')
print('{0}{1}'.format(s1,s2))
字符串的去重
s='helloworldhelloworlddasdfrgrtg5fefrf'
#字符串拼接及 not in
new_s=''
for item in s:
if item not in new_s:
new_s+=item #拼接
print(new_s)
#使用索引 + not in
new_s2=''
for i in range(len(s)):
if s[i] not in new_s2:
new_s2+=s[i]
print(new_s2)
# 通過集合去重+列表排序
new_s3=set(s)
lst=list(new_s3)
lst.sort(key=s.index)
print(''.join(lst))
結(jié)果:文章來源地址http://www.zghlxwxcb.cn/news/detail-761277.html
D:\Python_Home\venv\Scripts\python.exe D:\Python_Home\chap6\示例6-8字符串的去重操作.py
helowrdasfgt5
helowrdasfgt5
helowrdasfgt5
到了這里,關(guān)于Python入門-字符串Str的文章就介紹完了。如果您還想了解更多內(nèi)容,請在右上角搜索TOY模板網(wǎng)以前的文章或繼續(xù)瀏覽下面的相關(guān)文章,希望大家以后多多支持TOY模板網(wǎng)!