在 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'

在 Python 中为字符串添加 X 个空格

第一个示例使用乘法运算符将空格添加到字符串。

乘法运算符可用于将字符串重复指定次数。

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() 方法采用填充字符串的总长度。