Python 使用格式和变量将字符串居中
我想知道如何写一个像这样居中的字符串:Python 使用格式和变量将字符串居中,python,printing,format,Python,Printing,Format,我想知道如何写一个像这样居中的字符串: print("{0:^30s}".format("hello")) 但是我希望30是一个变量,因此如果我向函数发送一个“num=5”,它将是{0:^5s},任何人都知道正确的语法?格式说明符本身可以包含替换字段。您可以使用: print("{0:^{num}s}".format("hello", num=30)) # hello 另一种方法可能是使用.center()方法: string = "hello" # num
print("{0:^30s}".format("hello"))
但是我希望30是一个变量,因此如果我向函数发送一个“num=5”,它将是{0:^5s},任何人都知道正确的语法?格式说明符本身可以包含替换字段。您可以使用:
print("{0:^{num}s}".format("hello", num=30))
# hello
另一种方法可能是使用
.center()
方法:
string = "hello"
# num = 5 or below
num = function(num)
print(a.center(len(a) + num, ' '))
得到包裹
Termisize是一个跨平台python模块,用于获取终端大小
安装Termisize-pip安装Termisize
代码
但是如果我想通过一个函数传递num,我应该在那里写num吗?函数(num),而不是num=30,num?@Alex:如果有变量
num
,则可以使用“{0:^{num}s}.format”(“hello”,num=num)
”或“{0:^{1}s}.format”(“hello”,num)
。
import termisize as t
name = "Terabyte"
known_as = "tbhaxor"
cols = t.get_cols() # gets columns number i.e width of terminal
msg = "My Name is {0} and i am also known as {1}".format(name, known_as)
print( msg.center(cols) )