字串的對齊 python

2021-10-02 13:05:53 字數 2207 閱讀 2535

根據cookbook進行整理

a =

"hello world"

b = a.ljust(20)

#預設為填充空格,將長度擴充套件至20

print

(b)#"hello world "

c = a.ljust(20,

"*")

#在字串中填充*,將長度擴充套件至20,並將原字串左對齊

print

(c)#hello world*********

a =

"hello world"

b = a.rjust(20)

#預設為填充空格,將長度擴充套件至20

print

(b)#" hello world"

c = a.rjust(20,

"*")

#在字串中填充*,將長度擴充套件至20,並將原字串右對齊

print

(c)#*********hello world

a =

"hello world"

b = a.center(20)

#預設為填充空格,將長度擴充套件至20

print

(b)#" hello world "

c = a.center(20,

"*")

#在字串中填充*,將長度擴充套件至20,並將原字串居中

print

(c)#****hello world*****

a =

"hello world"

b =format

(a,"<20"

)#擴充套件字串長度至20,左對齊

print

(b)#"hello world "

a =

"hello world"

b =format

(a,"*<20"

)#擴充套件字串長度至20,左對齊

print

(b)#hello world*********

a =

"hello world"

b =format

(a,"<20"

)#擴充套件字串長度至20,左對齊

print

(b)#" hello world"

a =

"hello world"

b =format

(a,"*>20"

)#擴充套件字串長度至20,左對齊

print

(b)#*********hello world

a =

"hello world"

b =format

(a,"^20"

)#擴充套件字串長度至20,左對齊

print

(b)#" hello world "

a =

"hello world"

b =format

(a,"*^20"

)#擴充套件字串長度至20,左對齊

print

(b)#"****hello world*****"

a =

1.23245

b =format

(a,"<10"

)print

(b)#"1.23245 "

c =format

(a,"<10.2f"

)print

(c)#"1.23 "

a =''.

format

("hello"

,"world"

)print

(a)#" hello world"

a =

"hello world"

b ="%-20s"

%aprint

(b)#"hello world "

c ="%20s"

%aprint

(c)# hello world

Python 秘籍 字串對齊

問題 你想通過某種對齊方式來格式化字串 解決方案 對於基本的字串對齊操作,可以使用字串的 ljust rjust 和 center 方法。比如 text hello world text.ljust 20 hello world text.rjust 20 hello world text.cent...

001 004 Python 字串對齊

如下 encoding utf 8 print 中國 字串對齊 print abc中國 ljust 20 abc中國 rjust 20 abc中國 center 20 print u u abc中國 ljust 20 u u abc中國 rjust 20 u u abc中國 center 20 u ...

Python 兩字串對齊(預比對)

coding utf 8 created on sun jun 7 23 34 21 2020 author kerui def edit str1,str2 matrix i j for j in range len str1 1 for i in range len str2 1 print m...