Python高級方法
字符串進行左, 右, 居中對齊
1. 使用字符串的str.ljust()
str.rjust()
str.center()
s爲需要對齊的字符串,第2個參數爲插入其他字符的形式,第1個參數爲總的數量。(包括字符串s)
s.ljust(20,"*")
輸出:'xyz*****************'
s.rjust(20,"*")
輸出:'*****************xyz'
s.center(20,"*")
輸出:'********xyz*********'
2. 使用format() 傳遞類似’<20’,’>20’,’^20’參數
format(s,'*<20') # 左對齊
輸出:'xyz*****************'
format(s,'*>20') # 右對齊
輸出:'*****************xyz'
format(s,'*^20') # 居中對齊
輸出:'********xyz*********'
檢查字符串開頭內容:startswith()方法
startswith()
方法用於檢查字符串是否是以指定子字符串開頭,如果是則返回True
,否則返回 False
。如果參數 beg
和 end
指定值,則在指定範圍內檢查。
1. 語法
str.startswith(str, beg=0,end=len(string))
2. 例子
str = "this is string example....wow!!!";
print str.startswith( 'this' );
print str.startswith( 'is', 2, 4 );
print str.startswith( 'this', 2, 4 );
返回結果:
True
True
False