1. 使用字符串的`center()`方法:
text = "Hello, Python!"
width = 30
centered_text = text.center(width)
print(centered_text)
2. 使用`str.format()`方法:
text = "Hello, Python!"
width = 30
centered_text = "{:^{width}}".format(text, width=width)
print(centered_text)
3. 使用第三方库`textwrap`中的`center()`方法:
import textwrap
text = "Hello, Python!"
width = 30
centered_text = textwrap.center(text, width)
print(centered_text)
4. 自定义函数实现文本居中:
def center_text(text, width):
return text.center(width)
text = "Hello, Python!"
width = 30
centered_text = center_text(text, width)
print(centered_text)
以上方法都可以实现文本居中。您可以根据需要选择合适的方法