python基礎 - 字符串做

split(sep=None, maxsplip=-1)python

從左到右git

sep 指定分隔字符串,缺省狀況下空白字符串,指定的字符串會被切掉api

maxsplit 指定分隔次數,-1 表示遍歷函數

rsplit(sep=None, maxsplit=-1)spa

從右到左code

...orm

splitlines([keepends])server

按照行來分隔字符串對象

keepends 指的是是否保留行分隔符索引

行分隔符包括 \n, \r\n, \r 等

partition(sep)

從左到右,遇到分隔符就把字符串分割成兩個部分,返回頭,分隔符,尾三部分的三元組,若是沒有找到分隔符,就返回頭,兩個空元素的三元組。

sep 必須指定。

rpartition(seq)

從右到左

字符串大小寫

upper(): 全大寫

lower(): 全小寫

swapcase(): 交互大小寫

字符串排版

title(): 標題的每一個單詞都大寫

capitalize: 首個單詞大寫

center(width [,fillchar]): width 打印寬度,fillchar: 填充的字符

zfill(width): width 打印寬度,居右,左邊用0填充

ljust(width[,fillchar]): 左對齊

rjust(width[,fillchar]): 右對齊

字符串修改

replace(old, new[,count]):

找到匹配字符串換爲新串,count指定替換幾回,不指定所有替換。

strip([chars]):

從字符串兩端去除chars中字符,沒有指定chars去除兩端空格

字符串查找

find(sub[,start[,end]]):

在指定區間 [start, end],從左到右,查找子串 sub 。找到返回索引,沒有返回 -1

rfind(sub[,start[,end]])

從右到左

index(sub[,start[,end]])

在指定區間[start, end],從左至右,查找子串sub。找到返回索引,沒有找到拋出異常ValueError

count(sub[,start[,end]])

在指定區間 [start, end], 從左到右,統計子串 sub 出現的次數。

字符串判斷

endswith(suffix[,start[,end]]):

在指定區間 [start, end],字符串是不是 suffix 結尾,返回 bool

startswith(prefix[,start[,end]]):

在指定區間 [start, end], 字符串是不是 prefix 開頭, 返回 bool

is 系列

isalnum(): 是不是字母和數字組成

isalpha(): 是不是字母

isdecimal(): 是否只包含十進制數字

isdigit(): 是否所有數字(0-9)

islower(): 是否全都是小寫

isupper(): 是否所有大寫

isspace(): 是否只包含空白字符

字符串格式化

printf-style formatting

"I'm %03"%(20)

"I like %s"%'Python'

"I am %-5d"%(20)

format 函數格式字符串語法

"{} {xxx}".format(*args,**kwargs)
# args 是位置參數,是一個元組
# kwargs 是關鍵字參數,是一個字典
# 花括號表示佔位符
# {} 表示按順序匹配位置參數,{n}
# 表示取位置參數索引爲n的值
# {xxx} 表示在關鍵字參數中搜索名稱一致的
# {{}} 表示打印花括號
# 位置參數
"{},{}".format('1111',8888) # 這就是按照位置順序用位置參數替換前面的格式字符串的佔位符中
# 關鍵字參數或命名參數
"{server}{1}:{0}",format(8888,'192.168.0.1',server='Web Server Info')
# 訪問元素
"{0[0]}.{0[1]}".format(('magedu','com'))
# 對象屬性訪問
Point = namedtuple('Point','x y')
p = Point(3,5)
"{{{0.x},{0.y}}}".format(p)
'{0}*{1}={2:>2}'.format(3,2,2*3) # 3*2=06
'{:>}' # 右對齊
'{:<}' # 左對齊
'{:^30}'.format('centered') # ^ 居中
'{:*^30}'.format('centered') # 居中並以 * 填充

進制

'int:{0:d};hex:{0:x};oct:{0:o};bin:{0:b}'.format(42)
'int:{0:d};hex:{0:#x};oct:(0:#o);bin:{0:#b}'.format(42) # 會顯示進制符號

octets = [192,168,0,1]
'{:02X}{:02X}{:02X}{:02x}'.format(*octets) # * 表示解構
相關文章
相關標籤/搜索