MST

星途 面试题库

面试题:Python中字符串格式化输出定制之填充与对齐

在Python中,使用%s格式化输出时,如何实现将字符串进行居中对齐,并在两侧填充特定字符(比如'*')?假设字符串为'Hello',要求总宽度为10个字符,请写出代码实现。
23.2万 热度难度
编程语言Python

知识考点

AI 面试

面试题答案

一键面试
string = 'Hello'
formatted_string = ("%*s*" % ((10 - len(string) - 1) // 2, string)).center(10, '*')
print(formatted_string)