python使用字符串的格式化方法来设置字符串的固定长度

可以使用字符串的 format() 方法或者 f-string 来实现。

使用 format() 方法:

string = "hello"
formatted_string = "{:<10}".format(string)
print(formatted_string)  # 输出:"hello     "

在上面的例子中,{:<10} 表示将字符串左对齐,并且占据 10 个字符的宽度。

使用 f-string:

string = "hello"
formatted_string = f"{
      
      string:<10}"
print(formatted_string)  # 输出:"hello     "

在上面的例子中,f"{string:<10}" 表示将字符串左对齐,并且占据 10 个字符的宽度。

这样就可以将字符串固定到指定的长度,如果原始字符串长度小于指定长度,会在右侧填充空格以达到指定长度。你也可以根据需要使用其他填充字符,比如>表示右对齐,或者使用其他字符来填充。

猜你喜欢

转载自blog.csdn.net/qq_16792139/article/details/132673489
今日推荐