1.字符串格式化
格式化符號 說明
%c 轉換成字符(ASCII 碼值,或者長度爲一的字符串)
%r 優先用repr()函數進行字符串轉換
%s 優先用str()函數進行字符串轉換
%d / %i 轉成有符號十進制數
%u 轉成無符號十進制數
%o 轉成無符號八進制數
%x / %X 轉成無符號十六進制數(x / X 代表轉換後的十六進制字符的大小寫)
%e / %E 轉成科學計數法(e / E控制輸出e / E)
%f / %F 轉成浮點數(小數部分自然截斷)
%g / %G %e和%f / %E和%F 的簡寫
%% 輸出% (格式化字符串裏面包括百分號,那麼必須使用%%)
2.字符串常用方法
①find()和rfind方法分別用來查找一個字符串在另一個字符串指定範圍(默認是整個字符串)中首次和最後一次出現的位置,如果不存在則返回-1;
②index()和rindex()方法用來返回一個字符串在另一個字符串指定範圍中首次和最後一次出現的位置,如果不存在則拋出異常;③count()方法用來返回一個字符串在另一個字符串中出現的次數。
④split()和rsplit()方法分別用來以指定字符爲分隔符,將字符串左端和右端開始將其分割成多個字符串,並返回包含分割結果的列表;
⑤partition()和rpartition()用來以指定字符串爲分隔符將原字符串分割爲3部分,即分隔符前的字符串、分隔符字符串、分隔符後的字符串,如果指定的分隔符不在原字符串中,則返回原字符串和兩個空字符串。
#對於split()和rsplit()方法,如果不指定分隔符,則字符串中的任何空白符號(包括空格、換行符、製表符等等)都將被認爲是分隔符,返回包含最終分割結果的列表。
>>> s = 'hello world \n\n My name is Dong '
>>> s.split()
['hello', 'world', 'My', 'name', 'is', 'Dong']
>>> s = '\n\nhello world \n\n\n My name is Dong '
>>> s.split()
['hello', 'world', 'My', 'name', 'is', 'Dong']
>>> s = '\n\nhello\t\t world \n\n\n My name\t is Dong '
>>> s.split()
['hello', 'world', 'My', 'name', 'is', 'Dong']
#split()和rsplit()方法還允許指定最大分割次數,例如:
>>> s = '\n\nhello\t\t world \n\n\n My name is Dong '
>>> s.split(None,1)
['hello', 'world \n\n\n My name is Dong ']
>>> s.rsplit(None,1)
['\n\nhello\t\t world \n\n\n My name is', 'Dong']
>>> s.split(None,2)
['hello', 'world', 'My name is Dong ']
>>> s.rsplit(None,2)
['\n\nhello\t\t world \n\n\n My name', 'is', 'Dong']
>>> s.split(None,5)
['hello', 'world', 'My', 'name', 'is', 'Dong ']
>>> s.split(None,6)
['hello', 'world', 'My', 'name', 'is', 'Dong']
⑥join():字符串聯接
例子:
>>> li=["apple", "peach", "banana", "pear"]
>>> sep=","
>>> s=sep.join(li)
>>> s
"apple,peach,banana,pear"
不推薦使用+連接字符串,優先使用join()方法
⑦lower()、upper()、capitalize()、title()、swapcase()
將字符串轉換爲小寫、大寫字符串、將字符串首字母變爲大寫、將每個單詞的首字母變爲大寫以及大小寫互換。
⑧replace():查找替換
例:
>>> s="中國,中國"
>>> print s
中國,中國
>>>s2=s.replace("中國", "中華人民共和國")
>>> print s2
中華人民共和國,中華人民共和國
⑨maketrans()和translate:
生成映射表函數maketrans和按映射表關係轉換字符串函數translate
例:
>>> import string
>>> table=string.maketrans("abcdef123","uvwxyz@#$")
>>> s="Python is a greate programming language. I like it!"
>>> s.translate(table)
"Python is u gryuty progrumming lunguugy. I liky it!"
>>> s.translate(table,"gtm") #第二個參數表示要刪除的字符
"Pyhon is u ryuy proruin lunuuy. I liky i!"
⑩strip()、rstrip()、lstrip()
這幾個方法分別用來刪除兩端、右端或左端的空格或連續的指定字符。
(11)eval()
把任意字符串轉化爲python表達式並進行求值
>>> eval("3+4")
7
(12)關鍵字in
成員判斷
>>> "a" in "abcde"
True
(13)s.startwith(t)、s.endswith(t)
判斷字符串是否以指定字符串開始或結束
>>> import os
>>> [filename for filename in os.listdir(r'c:\\') if filename.endswith(('.bmp','.jpg','.gif'))]
(14)center()、ljust()、rjust()
返回指定寬度的新字符串,原字符串居中、左對齊或右對齊出現在新字符串中,如果指定寬度大於字符串長度,則使用指定的字符(默認爲空格)進行填充。
>>> 'Hello world!'.center(20)
' Hello world! '
format函數
format是python2.6新增的一個格式化字符串的方法,相對於老版的%格式方法,它有很多優點。
1.不需要理會數據類型的問題,在%方法中%s只能替代字符串類型
2.單個參數可以多次輸出,參數順序可以不相同
3.填充方式十分靈活,對齊方式十分強大
4.官方推薦用的方式,%方式將會在後面的版本被淘汰
一 填充
1.通過位置來填充字符串
>>> print('hello {0} i am {0}'.format('pipi','papa'))
hello pipi i am pipi
>>>
foramt會把參數按位置順序來填充到字符串中,第一個參數是0,然後1 ……
也可以不輸入數字,這樣也會按順序來填充
同一個參數可以填充多次,這個是format比%先進的地方
2.通過key來填充
print('hello {name1} i am {name2}'.format(name1='Kevin',name2='Tom'))
3.通過下標填充
>>> lis=['kate','peta']
>>> print('hi {name[0]} , i am {name[1]}'.format(name=lis))
hi kate , i am peta
>>>
4.通過字典的key
>>>name={'na1':'kaka','na2':'jiujiu'}
>>> print('{name[na1]} is {name[na2]}'.format(name=name))
kaka is jiujiu
>>>
5.通過對象的屬性
class Names():
name1='Kevin'
name2='Tom'
print('hello {names.name1} i am {names.name2}'.format(names=Names))
6.使用魔法方法
>>> args=['lu']
>>> kwargs = {'name1': 'Kevin', 'name2': 'Tom'}
>>> print('hello {name1} {} i am {name2}'.format(*args, **kwargs))
hello Kevin lu i am Tom
7.小數的精確
>>> print('{:.3f} {:.2f}'.format(1.666,1.666))
1.666 1.67
二 格式轉換
b、d、o、x分別是二進制、十進制、八進制、十六進制。
數字 格式 輸出 描述
3.1415926 {:.2f} 3.14 保留小數點後兩位
-1 {:+.2f} -1 帶符號保留小數點後兩位
2.71828 {:.0f} 3 不帶小數
1000000 {:,} 1,000,000 以逗號分隔的數字格式
0.25 {:.2%} 25.00% 百分比格式
1000000000 {:.2e} 1.00E+09 指數記法
25 {0:b} 11001 轉換成二進制
25 {0:d} 25 轉換成十進制
25 {0:o} 31 轉換成八進制
25 {0:x} 19 轉換成十六進制
>>> print('{:.3f}'.format(3.1415926))
3.142
>>>