搜尋
首頁後端開發Python教學python之Character string的實例講解

python之Character string的實例講解

Sep 25, 2017 am 11:25 AM
characterpythonstring

下面小編就為大家帶來一篇python之Character string(實例講解)。小編覺得蠻不錯的,現在就分享給大家,也給大家做個參考。一起跟著小編過來看看吧

1、python字串

字串是 Python 中最常用的資料型別。我們可以使用引號('或")來建立字串,l

Python不支援單字元類型,單字元也在Python也是作為一個字串使用。


>>> var1 = 'hello python' #定义字符串
>>> print(var1[0]) #切片截取,从0开始,不包括截取尾数
h
>>> print(var1[0:5])
hello
>>> print(var1[-6:])
python
>>> var2 = var1[0:6]+'world' #截取字符并拼接赋值给新变量
>>> print(var2)
hello world

2、python轉義字元

#\  :在行尾時,為續行符號

#\\  :反斜線轉義,輸出'\'

\'  :單引號轉義

\"  :雙引號轉義

#\b  :退格(backspace)

\n  :換行

\v  :縱向製表符

\t  :橫向製表符

\r  :回車

#\f  :換頁

3、python字串運算子

(+)拼接,(*)重複,( [])索引,([:])切片,(in)成員判斷,(not in)非成員判斷,(r/R)元素輸出字串


>>> var1 = 'hello'
>>> var2 = 'python'
>>> print(var1+var2) #拼接字符串
hellopython
>>> print(var1*3) #重复输出字符串
hellohellohello
>>> print(var1[0]) #索引字符串
h
>>> print(var1[3:]) #索引切片
lo
>>> 'e' in var1 #判断字符串是否在变量中
True
>>> 'p' not in var1 #判断字符串是否不在变量中
True
>>> print("he\tllo \n") 
he llo 
>>> print(r"he\tllo \n") #原始输出字符串,也就是原始输出转义字符
he\tllo \n

4、格式化字串

Python 支援格式化字串的輸出。儘管這樣可能會用到非常複雜的表達式,但最基本的用法是將一個值插入到一個有字串格式符 %s 的字串中。

在 Python 中,字串格式化使用與 C 中 sprintf 函數一樣的語法。

python字串格式化符號:

#%x#%X%f##%e用科學計數法格式化浮點數%E#同%e,用科學計數法格式化浮點數%g%f和%e的簡寫#%G%f 和%E 的簡寫
#%c 格式化字元及其ASCII碼
%s 格式化字串
#%d 格式化整數
#%u 格式化無符號整數
%o 格式化無符號八進位數
格式化無符號十六進位數
格式化無符號十六進制數(大寫)
格式化浮點數數字,可指定小數點後的精確度

%p

以十六進位數格式化變數的位址#格式化運算子輔助指令:*定義寬度或小數點精確度用做左對齊在正數前面顯示加號( + )在正數前面顯示空格##在八進位數前面顯示零('0'),在十六進位前面顯示'0x'或'0X'(取決於用的是'x'還是'X')顯示的數字前面填入'0'而不是預設的空格'%%'輸出單一的'%'映射變數(字典參數)
##-
+
#0
%
(var)


m.n.

#m 是顯示的最小總寬度,n 是小數點後的位數(如果可用的話)


>>> print("ascii:%c"%'s') #格式化输出字符
ascii:s
>>> print("ascii:%c"%'1') #格式化输出数字
ascii:1
>>> print("str:%s"%'character string') #格式化字符串
str:character string
>>> print("str:%d"%888) #格式化整数
str:888
>>> print("str:%f"%888) #格式浮点数
str:888.000000
>>> print("str:%e"%888) #格式化科学计数浮点数
str:8.880000e+02
>>> print("str:%E"%888) #同上
str:8.880000E+02
>>> print("str:%G"%888) #%f和%E的简写
str:888

>>> print("str:%20f"%888.089) #定义20宽度输出
str:  888.089000
>>> print("str:%-20f"%888.089) #用左对齐
str:888.089000  
>>> print("str:%+20f"%888.089) #在正数前显示加号
str:  +888.089000
>>> print("str:%+-20f"%888.089) #左对齐显示加号
str:+888.089000  
>>> print("str:%020f"%888.089) #以0填充默认的空格
str:0000000000888.089000
>>> print("str:%%%20f"%888.089) #在数字前输入%号
str:%  888.089000
>>> print("str:%%%-20f"%888.089) #左对齐输出%号
str:%888.089000  
>>> print("str:%20.3f"%888.089) #显示最小总宽度20,小数点后位数为3位
str:  888.089

自python2.6開始,增加格式化字串函數str.format():

用法:它透過{}和:來代替%位置參數不受順序約束,且可以為{}空,只要format裡有相對應的參數值即可,如參數值不夠就會報錯,參數索引從0開,傳入位置參數清單可用*列表


In [27]: '{}+{}={}'.format(1,2,3) #格式化按顺序应用参数值
Out[27]: '1+2=3'
In [28]: '{2}-{1}={0}'.format(1,2,3) #指定顺序应用参数值
Out[28]: '3-2=1'
In [29]: '{0}+{0}={1}'.format(2,3) #指定参数可以重复使用
Out[29]: '2+2=3'
In [30]: '{}+{}={}'.format(2,3) #如不指定顺序,format参数不够就会报错
---------------------------------------------------------------------------
IndexError    Traceback (most recent call last)
<ipython-input-30-29f40e412920> in <module>()
----> 1 &#39;{}+{}={}&#39;.format(2,3)
IndexError: tuple index out of range

In [31]: l1 = [2,4,8] 
In [32]: &#39;{}*{}={}&#39;.format(*l1) #使用列表引用参数值
Out[32]: &#39;2*4=8&#39;

In [33]: dct = {&#39;name&#39;:&#39;python&#39;,&#39;age&#39;:20} #定义字典
In [35]: &#39;welcom to {name},age is {age}&#39;.format(name=&#39;qi&#39;,age=28) #变量引用
Out[35]: &#39;welcom to qi,age is 28&#39;

In [36]: &#39;welcom to {name},age is {age}&#39;.format(**dct) #使用**引用字典参数必须填写key值
Out[36]: &#39;welcom to python,age is 20&#39;

填充与格式化:
In [53]: "{0: >20}".format("string") #从0位开始已空格填充20宽度左对齐
Out[53]: &#39;  string&#39;

In [54]: "{0:&>20}".format("string")
Out[54]: &#39;&&&&&&&&&&&&&&string&#39;

In [55]: "{0:#>20}".format("string") #使用#号会有个小bug
 ....: 
Out[55]: &#39;##############string&#39;

In [60]: &#39;{0:+<20}&#39;.format("string") #向右对齐填充+
Out[60]: &#39;string++++++++++++++&#39;

In [61]: &#39;{0:+^20}&#39;.format("string") #剧中对齐填充+
Out[61]: &#39;+++++++string+++++++&#39;

精度与进制:
>>> &#39;{0:.3f}&#39;.format(10/3) #小数位进度格式化
&#39;3.333&#39;
>>> &#39;{0:b}&#39;.format(8) #格式化二进制
&#39;1000&#39;
>>> &#39;{0:o}&#39;.format(9) #格式化八进制
&#39;11&#39;
>>> &#39;{0:x}&#39;.format(26) #格式化十六进制
&#39;1a&#39;
>>> &#39;{0:,}&#39;.format(123456789) #千分位格式化
&#39;123,456,789&#39;

使用索引:
>>> l2 = [&#39;AA&#39;,{&#39;bb&#39;:&#39;cc&#39;},(&#39;d&#39;,&#39;e&#39;)] #列表索引引用
>>> &#39;outing:{0[0]}&#39;.format(l2) 
&#39;outing:AA&#39;
>>> &#39;outing:{0[0]},{0[1]}&#39;.format(l2) #将列表当成一个元素,在其中索引值
"outing:AA,{&#39;bb&#39;: &#39;cc&#39;}"

######5、python的字串方法####### ###########
>>> s = &#39;i mi to&#39; #将字符串的第一个字符改为大写
>>> s.capitalize()
&#39;I mi to&#39;

>>> s = &#39;I MI TO&#39; #将字符串所有字符改为小写
>>> s.casefold()
&#39;i mi to&#39;

>>> s.center(15) #将字符串剧中,并用空格将字符串填充长度,如指定长度小于实际长度则没有效果
&#39; I MI TO &#39;

>>> s = &#39;abcabcabcabc&#39; #返回sub在字符串里出现的次数,start,end为可选参数,决定范围
>>> s.count(&#39;a&#39;,0,12)
4
>>> s.encode(encoding=&#39;utf-8&#39;,errors=&#39;strict&#39;) #以encoding指定的编码格式对字符串进行编码
b&#39;abcabcabcabc&#39;
>>> s.endswith(&#39;abc&#39;,1,12) #检查字符串是否以sub结尾,是返回True,否返回False,start,end为可选参数,决定范围
True

>>> s = &#39;a\tb\tc&#39;
>>> s.expandtabs(4) #把字符串的tab字符(\t)转化为空格,如不指定tabsize,默认为8个空格
&#39;a b c&#39;

>>> s.find(&#39;b&#39;) #检测字符串是否在字符串中,如在则返回索引,否则返回-1,可指定起始值。
2

>>> s=&#39;hello python&#39;
>>> s.index(&#39;hello&#39;) # 类似find(),不同在于如果sub不在字符串中,返回异常
0 

>>> s.isalnum() #有空格返回false
False
>>> s=&#39;hellopython&#39;
>>> s.isalnum() #如果字符串至少有一个字符,并且所有字符都是字母或数字则返回True,否则False
True
>>> s.isalpha() #如果字符串至少有一个字符,并且所有字符都是字母则返回True,否则False
True

>>> s = &#39;123&#39;
>>> s.isdigit() #如果字符串只包含数字则返回True,否则返回False
True

>>> s = &#39;123&#39;
>>> s.isdecimal() #如果字符串只包含十进制数字则返回True,否则返回False
True
>>> s= &#39;ox123&#39;
>>> s.isdecimal()
False
>>> s = &#39;0.33&#39;
>>> s.isdecimal()
False

>>> s = &#39;abc&#39;
>>> s.islower() #如果字符中至少包含一个能区分大小写的字符,并且这些字符都是小写则返回True,否则返回Flase
True
>>> s = &#39;Abc&#39;
>>> s.islower()
False

>>> s = &#39;ABC&#39;
>>> s.isupper() #果字符中至少包含一个能区分大小写的字符,并且这些字符都是大写则返回True,否则返回Flase
True
>>> s = &#39;ABc&#39;
>>> s.isupper()
False
>>> 

>>> s = &#39;123&#39;
>>> s.isnumeric() #如果字符串只包含数字字符,则返回True,否则返回False
True
>>> s = &#39;123a&#39;
>>> s.isnumeric()
False

>>> &#39;def&#39;.isidentifier() #判断字符串是否包含该语言的保留字
True

>>> &#39;aaa&#39;.isprintable() #判断是否可以打印
True

>>> &#39;&#39;.isspace()
False
>>> &#39; &#39;.isspace() #判断字符串中至少有一个字符且所有都是空格,否则返回false
True
>>> &#39; a&#39;.isspace()
False

>>> &#39;Abc&#39;.istitle() #判断是否是标题 格式,可以理解为首字母大写。
True
>>> &#39;aBC&#39;.istitle()
False

>>> s = &#39;123&#39;
>>> &#39;_&#39;.join(s) #返回一个用指定字符串分隔的字,或者是将指定字符加入到另一个字符中。
&#39;1_2_3&#39;
>>> s.join(&#39;abc&#39;)
&#39;a123b123c&#39;

>>> s = &#39;ABC&#39;
>>> s.lower() #返回的是指定字符串的拷贝,并转化成小写
&#39;abc&#39;

>>> s.ljust(10,&#39;+&#39;) #可以指定宽度,以及填充字符串,返回的是按宽度,填充字符串格式化后的左对齐的字符串。
&#39;ABC+++++++&#39;

>>> &#39;aaabccc&#39;.partition(&#39;b&#39;) #在字符串中查找指定的字符,如找到则返回字符前部分,字符本身和后部分,如没找到则返回字符串和两个空字符串。
(&#39;aaa&#39;, &#39;b&#39;, &#39;ccc&#39;)
>>> &#39;aaabccc&#39;.partition(&#39;e&#39;)
(&#39;aaabccc&#39;, &#39;&#39;, &#39;&#39;)

>>> &#39;aaabccc&#39;.rpartition(&#39;b&#39;) #与partition一样,但是是从右边开始
(&#39;aaa&#39;, &#39;b&#39;, &#39;ccc&#39;)
>>> &#39;aaabccc&#39;.rpartition(&#39;c&#39;)
(&#39;aaabcc&#39;, &#39;c&#39;, &#39;&#39;)


>>> &#39;aaaaabbcc&#39;.replace(&#39;a&#39;,&#39;A&#39;) #用指定字符串替换指定字符串,如果不指定替换次数,则替换所有
&#39;AAAAAbbcc&#39;
>>> &#39;aaaaabbcc&#39;.replace(&#39;a&#39;,&#39;A&#39;,2)
&#39;AAaaabbcc&#39;

>>> &#39;aabbcc&#39;.rfind(&#39;a&#39;) #返回指定子串的最高索引,如果没找到则返回-1,可以指定要开始替换的起始,结束位置。
1
>>> &#39;aabbcc&#39;.rfind(&#39;e&#39;)
-1
>>> &#39;aabbcc&#39;.rindex(&#39;a&#39;) #与上面的rfind一样,只是如果没找到不是返回-1,而是触发错误
1
>>> &#39;aabbcc&#39;.rindex(&#39;e&#39;)
Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
ValueError: substring not found

>>> &#39;aa&#39;.rjust(10,&#39;+&#39;) #与ljust()相对应,右对齐
&#39;++++++++aa&#39;
>>> &#39;aa&#39;.ljust(10,&#39;+&#39;)
&#39;aa++++++++&#39;

>>> &#39;aabccbddbee&#39;.split(&#39;b&#39;) ##按指定字符串对目标字符串进行切割,可以指定切割次数
[&#39;aa&#39;, &#39;cc&#39;, &#39;dd&#39;, &#39;ee&#39;]
>>> &#39;aabccbddbee&#39;.split(&#39;b&#39;,2)
[&#39;aa&#39;, &#39;cc&#39;, &#39;ddbee&#39;]

>>> &#39;aabccbddbee&#39;.rsplit(&#39;b&#39;,2) #与split作用相同,但是从右侧开始
[&#39;aabcc&#39;, &#39;dd&#39;, &#39;ee&#39;]

>>> &#39; aabb &#39;.strip() #移除字符串两侧的指定字符串,默认移除空格,需要注意的是可以指定多个字符
&#39;aabb&#39;
>>> &#39; aabb&#39;.strip(&#39;b&#39;)
&#39; aa&#39;
>>> &#39; aabb&#39;.strip(&#39;ab&#39;)
&#39; &#39;
>>> &#39;beaacebb&#39;.rstrip(&#39;eb&#39;) #与strip一样,从右侧删除指定字符,可以为多个
&#39;beaac&#39;

>>> &#39;aa\nbb\ncc\ndd&#39;.splitlines() #按换行符切割显示,如没指定keepends=True则将换行符移除。
[&#39;aa&#39;, &#39;bb&#39;, &#39;cc&#39;, &#39;dd&#39;]
>>> &#39;aa\nbb\ncc\ndd&#39;.splitlines(keepends=True)
[&#39;aa\n&#39;, &#39;bb\n&#39;, &#39;cc\n&#39;, &#39;dd&#39;]

>>> &#39;aabbc&#39;.startswith(&#39;a&#39;) #判断字符串是否以某个字符开头,可以是多字符
True
>>> &#39;aabbc&#39;.startswith(&#39;b&#39;)
False
>>> &#39;aabbc&#39;.startswith(&#39;aab&#39;)
True

>>> &#39;aaBBcc&#39;.swapcase() #转换大小写
&#39;AAbbCC&#39;

>>> &#39;wend is ok&#39;.title() #标题格式,首字母大写,其它字符小写
&#39;Wend Is Ok&#39;

>>> &#39;wend is ok&#39;.upper() #将字符全部转换成大写
&#39;WEND IS OK&#39;

>>> &#39;wend is ok&#39;.zfill(20) #这里的z指zero,用0将字符填充到指定长度
&#39;0000000000wend is ok&#39;

以上是python之Character string的實例講解的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn
Python:深入研究彙編和解釋Python:深入研究彙編和解釋May 12, 2025 am 12:14 AM

pythonisehybridmodeLofCompilation和interpretation:1)thepythoninterpretercompilesourcecececodeintoplatform- interpententbybytecode.2)thepythonvirtualmachine(pvm)thenexecutecutestestestestestesthisbytecode,ballancingEaseofuseEfuseWithPerformance。

Python是一種解釋或編譯語言,為什麼重要?Python是一種解釋或編譯語言,為什麼重要?May 12, 2025 am 12:09 AM

pythonisbothinterpretedAndCompiled.1)它的compiledTobyTecodeForportabilityAcrosplatforms.2)bytecodeisthenInterpreted,允許fordingfordforderynamictynamictymictymictymictyandrapiddefupment,儘管Ititmaybeslowerthananeflowerthanancompiledcompiledlanguages。

對於python中的循環時循環與循環:解釋了關鍵差異對於python中的循環時循環與循環:解釋了關鍵差異May 12, 2025 am 12:08 AM

在您的知識之際,而foroopsareideal insinAdvance中,而WhileLoopSareBetterForsituations則youneedtoloopuntilaconditionismet

循環時:實用指南循環時:實用指南May 12, 2025 am 12:07 AM

ForboopSareSusedwhenthentheneMberofiterationsiskNownInAdvance,而WhileLoopSareSareDestrationsDepportonAcondition.1)ForloopSareIdealForiteratingOverSequencesLikelistSorarrays.2)whileLeleLooleSuitableApeableableableableableableforscenarioscenarioswhereTheLeTheLeTheLeTeLoopContinusunuesuntilaspecificiccificcificCondond

Python:它是真正的解釋嗎?揭穿神話Python:它是真正的解釋嗎?揭穿神話May 12, 2025 am 12:05 AM

pythonisnotpuroly interpred; itosisehybridablectofbytecodecompilationandruntimeinterpretation.1)PythonCompiLessourceceCeceDintobyTecode,whitsthenexecececected bytybytybythepythepythepythonvirtirtualmachine(pvm).2)

與同一元素的Python串聯列表與同一元素的Python串聯列表May 11, 2025 am 12:08 AM

concatenateListSinpythonWithTheSamelements,使用:1)operatoTotakeEpduplicates,2)asettoremavelemavphicates,or3)listcompreanspherensionforcontroloverduplicates,每個methodhasdhasdifferentperferentperferentperforentperforentperforentperfornceandordorimplications。

解釋與編譯語言:Python的位置解釋與編譯語言:Python的位置May 11, 2025 am 12:07 AM

pythonisanterpretedlanguage,offeringosofuseandflexibilitybutfacingperformancelanceLimitationsInCricapplications.1)drightingedlanguageslikeLikeLikeLikeLikeLikeLikeLikeThonexecuteline-by-line,允許ImmediaMediaMediaMediaMediaMediateFeedBackAndBackAndRapidPrototypiD.2)compiledLanguagesLanguagesLagagesLikagesLikec/c thresst

循環時:您什麼時候在Python中使用?循環時:您什麼時候在Python中使用?May 11, 2025 am 12:05 AM

Useforloopswhenthenumberofiterationsisknowninadvance,andwhileloopswheniterationsdependonacondition.1)Forloopsareidealforsequenceslikelistsorranges.2)Whileloopssuitscenarioswheretheloopcontinuesuntilaspecificconditionismet,usefulforuserinputsoralgorit

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱門文章

熱工具

WebStorm Mac版

WebStorm Mac版

好用的JavaScript開發工具

SublimeText3漢化版

SublimeText3漢化版

中文版,非常好用

mPDF

mPDF

mPDF是一個PHP庫,可以從UTF-8編碼的HTML產生PDF檔案。原作者Ian Back編寫mPDF以從他的網站上「即時」輸出PDF文件,並處理不同的語言。與原始腳本如HTML2FPDF相比,它的速度較慢,並且在使用Unicode字體時產生的檔案較大,但支援CSS樣式等,並進行了大量增強。支援幾乎所有語言,包括RTL(阿拉伯語和希伯來語)和CJK(中日韓)。支援嵌套的區塊級元素(如P、DIV),

SublimeText3 Mac版

SublimeText3 Mac版

神級程式碼編輯軟體(SublimeText3)

PhpStorm Mac 版本

PhpStorm Mac 版本

最新(2018.2.1 )專業的PHP整合開發工具