zfill() 方法返回字符串的副本,其中 '0' 字符填充到左側。
用法:
str.zfill(width)
zfill()參數
zfill()
采用單個字符 width
。
width
指定從 zfill()
返回的字符串的長度,其中 0
數字填充到左側。
返回:
zfill()
返回字符串的副本,其中 0
填充到左側。返回字符串的長度取決於提供的width
。
- 假設字符串的初始長度為 10。並且,
width
指定為 15。在這種情況下,zfill()
返回字符串的副本,其中五個 '0' 數字填充到左側。 - 假設字符串的初始長度為 10。並且,
width
指定為 8。在這種情況下,zfill()
不會向左側填充 '0' 數字,而是返回原始字符串的副本。在這種情況下,返回字符串的長度為 10。
示例 1:zfill() 如何在 Python 中工作?
text = "program is fun"
print(text.zfill(15))
print(text.zfill(20))
print(text.zfill(10))
輸出
0program is fun 000000program is fun program is fun
如果字符串以符號前綴('+', '-')
, 0
開頭,則在第一個符號前綴字符之後填充數字。
示例 2:zfill() 如何與符號前綴一起使用?
number = "-290"
print(number.zfill(8))
number = "+290"
print(number.zfill(8))
text = "--random+text"
print(text.zfill(20))
輸出
-0000290 +0000290 -0000000-random+text
相關用法
- Python String Center()用法及代碼示例
- Python String decode()用法及代碼示例
- Python String join()用法及代碼示例
- Python String casefold()用法及代碼示例
- Python String isalnum()用法及代碼示例
- Python String rsplit()用法及代碼示例
- Python String startswith()用法及代碼示例
- Python String rpartition()用法及代碼示例
- Python String splitlines()用法及代碼示例
- Python String upper()用法及代碼示例
- Python String isprintable()用法及代碼示例
- Python String translate()用法及代碼示例
- Python String title()用法及代碼示例
- Python String replace()用法及代碼示例
- Python String split()用法及代碼示例
- Python String format_map()用法及代碼示例
- Python String max()用法及代碼示例
- Python String isspace()用法及代碼示例
- Python String strip()用法及代碼示例
- Python String Encode()用法及代碼示例
注:本文由純淨天空篩選整理自 Python String zfill()。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。