python字串總結

2021-08-31 13:59:16 字數 1424 閱讀 3083

總結一下在學習過程中遇到的字串問題。

格式化操作符(%)

"%"是python風格的字串格式化操作符

%r——優先用repr()函式進行字串轉換

%s——優先用str()函式進行字串轉換

%d / %i——轉成有符號十進位制數

%u——轉成無符號十進位制數

%o——轉成無符號八進位制數

%f / %f——轉成浮點數(小數部分自然截斷)

格式化操作符輔助符

-——用做左對齊

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

#——在八進位制數前面顯示零(0),在十六進製制前面顯示"0x"或者"0x"(取決 於用的是"x"還是"x")

字串內建函式format()

格式化字串函式str.format(),通過這個函式同樣可以對字串進行格式化處理。在format()函式中,使用「{}」符號來當作格式化操作符。

位置引數

根據format()裡邊的引數位置進行索引

print " is years old".format("wilber", 28)

print "{} is {} years old".format("wilber", 28)

print "hi, ! is years old".format("wilber", 28)關鍵字引數

print " is years old".format(name = "wilber", age = 28)下標引數

li = ["wilber", 28]

print " is years old".format(li)填充字元

格式.format(…)

後跟填充字元,不指定預設為空格填充,格式符有三種:^<>分別表示居中、左對齊和右對齊,且只能是乙個字元,格式符後跟寬度

print ''.format('3.14')

print ''.format('3.14')

還可以用來表示浮點精度:

print ''.format(3.1415926)

print ''.format(3.1415926)

字串內建函式

其中s均表示任意乙個字串

Python 字串總結

對字串的使用方法進行總結。1 建立字串 python中的字串用引號 或者 包括起來。2 修改字串 字串是不可修改的,類似元組。如 s abc s 0 z 會報錯。如果要增加或減少字元可通過建立乙個新的字串來實現,如 s abc s1 s 0 2 輸出 s1 ab s2 s def 輸出 s2 abc...

python 字串總結

1str1 hello,world 通過len函式計算字串的長度 print len str1 13 獲得字串首字母大寫的拷貝 print str1.capitalize hello,world 獲得字串變大寫後的拷貝 print str1.upper hello,world 從字串中查詢子串所在位...

python字串總結

認識字串 1.用單引號,雙引號,三引號作為定界符括起來的字串行 var1 hello,python var2 helloorld var3 good 字串輸出 1.直接輸出 print 1.我是英雄聯盟 info 2.我是王者榮耀 print info print 我是植物大戰殭屍 print 我是...