標籤:完全 else pytho 函數 方法 用法 第一個 nbsp 空格
一、字串運算子
下表執行個體變數 a 值為字串 "Hello",b 變數值為 "Python":
| 操作符 |
描述 |
執行個體 |
| + |
字串串連 |
>>>a + b ‘HelloPython‘ |
| * |
重複輸出字串 |
>>>a * 2 ‘HelloHello‘ |
| [] |
通過索引擷取字串中字元 |
>>>a[1] ‘e‘ |
| [ : ] |
截取字串中的一部分 |
>>>a[1:4] ‘ell‘ |
| in |
成員運算子 - 如果字串中包含給定的字元返回 True |
>>>"H" in a True |
| not in |
成員運算子 - 如果字串中不包含給定的字元返回 True |
>>>"M" not in a True |
| r/R |
原始字串 - 原始字串:所有的字串都是直接按照字面的意思來使用,沒有轉義特殊或不能列印的字元。 原始字串除在字串的第一個引號前加上字母"r"(可以大小寫)以外,與一般字元串有著幾乎完全相同的文法。 |
>>>print r‘\n‘ \n >>> print R‘\n‘ \n |
代碼:
1 a = "Hello" 2 b = "Python" 3 4 print "a + b 輸出結果:", a + b 5 print "a * 2 輸出結果:", a * 2 6 print "a[1] 輸出結果:", a[1] 7 print "a[1:4] 輸出結果:", a[1:4] 8 9 if( "H" in a) :10 print "H 在變數 a 中" 11 else :12 print "H 不在變數 a 中" 13 14 if( "M" not in a) :15 print "M 不在變數 a 中" 16 else :17 print "M 在變數 a 中"18 19 print r‘\n‘20 print R‘\n‘
程式執行結果為:
1 >>> 2 a + b 輸出結果: HelloPython 3 a * 2 輸出結果: HelloHello 4 a[1] 輸出結果: e 5 a[1:4] 輸出結果: ell 6 H 在變數 a 中 7 M 不在變數 a 中 8 \n 9 \n10 >>>
二、Python 字串格式化
Python 支援格式化字串的輸出 。儘管這樣可能會用到非常複雜的運算式,但最基本的用法是將一個值插入到一個有字串格式符 %s 的字串中。
代碼:
print "My name is %s and weight is %d kg!" % (‘Zara‘, 21)
運行結果
My name is Zara and weight is 21 kg!
三、Python 字串內建函數
如有字串 mystr = "Hello World SQYY"
1、find
檢測 str 是否包含在 mystr中,如果是返回開始的索引值,否則返回-1
mystr.find(str, start=0, end=len(mystr))
2、index
跟find()方法一樣,只不過如果str不在 mystr中會報一個異常.
mystr.index(str, start=0, end=len(mystr))
3、count
返回 str在start和end之間 在 mystr裡面出現的次數
mystr.count(str, start=0, end=len(mystr))
4、replace
把 mystr 中的 str1 替換成 str2,如果 count 指定,則替換不超過 count 次.
mystr.replace(str1, str2, mystr.count(str1))
5、split
切割,以 str 為分隔字元切片 mystr,如果 maxsplit有指定值,則僅分隔 maxsplit 個子字串
mystr.split(str=" ", 2)
6、capitalize
把字串的第一個字元大寫
mystr.capitalize()
7、startswith
檢查字串是否是以 obj 開頭, 是則返回 True,否則返回 False
mystr.startswith(obj)
8、endswith
檢查字串是否以obj結束,如果是返回True,否則返回 False.
mystr.endswith(obj)
9、lower
轉換 mystr 中所有大寫字元為小寫
mystr.lower()
10、upper
轉換 mystr 中的小寫字母為大寫
mystr.upper()
11、ljust
返回一個原字串靠左對齊,並使用空格填充至長度 width 的新字串
mystr.ljust(width)
12、rjust
返回一個原字串靠右對齊,並使用空格填充至長度 width 的新字串
mystr.rjust(width)
13、center
返回一個原字串置中,並使用空格填充至長度 width 的新字串
mystr.center(width)
14、lstrip
刪除 mystr 左邊的空格
mystr.lstrip()
15、rstrip
刪除 mystr 字串末尾的空格
mystr.rstrip()
16、rfind
類似於 find()函數,不過是從右邊開始尋找.
mystr.rfind(str, start=0,end=len(mystr) )
17、rindex
類似於 index(),不過是從右邊開始.
mystr.rindex( str, start=0,end=len(mystr))
18、partition
把mystr以str分割成三部分,str前,str和str後
mystr.partition(str)
19、rpartition
類似於 partition()函數,不過是從右邊開始.
mystr.rpartition(str)
20、splitlines
按照行分隔,返回一個包含各行作為元素的列表
mystr.splitlines()
21、isalnum
如果 mystr 所有字元都是字母或數字則返回 True,否則返回 False
mystr.isalnum()
22、isalpha
如果 mystr 所有字元都是字母 則返回 True,否則返回 False
mystr.isalpha()
23、isdigit
如果 mystr 只包含數字則返回 True 否則返回 False.
mystr.isdigit()
24、isspace
如果 mystr 中只包含空格,則返回 True,否則返回 False.
mystr.isspace()
25、isupper
如果 mystr 所有字元都是大寫,則返回 True,否則返回 False
mystr.isupper()
26、join
mystr 中每個字元後面插入str,構造出一個新的字串
1 mystr.join(str)
【代碼學習】PYTHON字串的常見操作