Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธี Left-pad String ด้วย Zeros ใน Python

มี 3 วิธีหลัก:

1. ใช้ rjust(width, fillchar)

>> '25'.rjust(6, '0')
'000025'
>>> 'Apollo'.rjust(10, '0')
'0000Apollo'

2. ใช้ % formatting

>> print("%06d" % 25)
'000025'

3. ใช้ zfill() (สร้างขึ้นมาเพื่อ목 đíchนี้)

>> '25'.zfill(6)
'000025'
>>> 'Apollo'.zfill(10)
'0000Apollo'

zfill() แนะนำมากที่สุด เพราะ readable และทำงานได้กับ non-numeric strings ด้วย