python 中的center()
函數有助於使字元串居中對齊。伴隨著這個函數,我們可以指定包含填充字元的字元串的寬度,以及需要在缺少的地方填充哪個字元。
**string.center(width[, fillchar])** #where width is an integer number
中心()參數:
center()
函數接受兩個參數。如果缺少參數「fillchar 」,它將使用空格(” “)作為默認值。填充在左側和右側完成。
參數 | 描述 | 必需/可選 |
---|---|---|
寬度 | 返回字元串的長度 | 需要 |
菲勒 | 插入字元 | 可選擇的 |
中心()返回值
方法返回一個字元串,該字元串以指定的寬度在中心對齊,並用給定的填充字元填充。它不會修改原始字元串。
| 投入 | 返回值 |
| 如果參數 | 返回一個字元串 |
Python 中center()
方法的示例
示例 1:默認為 fillchar 的 python center()
方法
string = "How are you?"
updated_string = string.center(24)
print("Centered String is: ", updated_string )
輸出:
Centered String is: How are you?
示例 2:帶有* fillchar 的 Python center()
方法
string = "How are you?"
updated_string = string.center(24, '*')
print("Centered String is: ", updated_string )
輸出:
Centered String is: ***How are you?****
原創文章,作者:小藍,如若轉載,請註明出處:https://www.506064.com/zh-tw/n/227371.html