在 Python 中为字符串添加 X 个空格
使用乘法运算符将 X 个空格添加到字符串,例如 result = my_str + ‘ ‘ * 2。 乘法运算符将重复空格指定的次数,加法 (+) 运算符将连接两个字符串。
my_str = 'abc'
# ✅ using addition operator with multiplication
result = ' ' * 2 + my_str
print(repr(result)) # ?️ ' abc'
result = my_str + ' ' * 2
print(repr(result)) # ?️ 'abc '
# ----------------------------------
num_of_spaces = 2
# ✅ add trailing spaces to string
result = my_str.ljust(len(my_str) + num_of_spaces, ' ')
print(repr(result)) # ?️ 'abc '
# ✅ add leading spaces to string
result = my_str.rjust(len(my_str) + num_of_spaces, ' ')
print(repr(result)) # ?️ ' abc'
第一个示例使用乘法运算符将空格添加到字符串。
乘法运算符可用于将字符串重复指定次数。
my_str = 'abc'
result = ' ' * 2 + my_str
print(repr(result)) # 👉️ ' abc'
result = my_str + ' ' * 2
print(repr(result)) # 👉️ 'abc '
我们只需将空格重复 N 次,然后使用加法运算符连接两个字符串。
我们可以使用乘法运算符将任何字符串重复 N 次。
print(repr(' ' * 2)) # 👉️ ' '
print(repr(' ' * 3)) # 👉️ ' '
print('-' * 2) # 👉️ '--'
print('-' * 3) # 👉️ '---'
或者,我们可以使用 str.ljust()
或 str.rjust()
方法。
my_str = 'abc'
num_of_spaces = 2
# ✅ add trailing spaces to string
result = my_str.ljust(len(my_str) + num_of_spaces, ' ')
print(repr(result)) # 👉️ 'abc '
# ✅ add leading spaces to string
result = my_str.rjust(len(my_str) + num_of_spaces, ' ')
print(repr(result)) # 👉️ ' abc'
str.ljust()
方法使用提供的填充字符将字符串的末尾填充到指定的宽度。
str.ljust()
方法采用以下 2 个参数:
- width 填充字符串的总长度
- fillchar 填充字符串的填充字符
str.rjust()
方法使用提供的填充字符将字符串的开头填充到指定的宽度。
我们将要添加到字符串的空格数添加到其长度,因为
ljust()
和rjust()
方法采用填充字符串的总长度。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。