简体   繁体   English

使用.format()打印一个不超过定义数量的空格并居中的字符串?

[英]Using .format() to print a string that does not exceed a defined number of spaces and is centered?

So Im trying to do three things here. 所以我想在这里做三件事。 1. Get the print statement below to be 16 spaces long 2. Cut off the extra = signs on eiter side of the name that cause it to be longer than 16. 3. Center the text so an equal amount of = signs are either side of the name 1.获取下面的打印声明长度为16个空格2.切掉名称上的额外=符号,使其长度超过16个.3。将文本居中,使等量=符号为任意一侧这个名字

This is my attempt... 这是我的尝试......

import random

name_list = ['Joe','Phil','Frank','Daniel']
name_choice = random.choice(name_list)
name_string = '======| {0} |======'.format(name_choice)
print('{0:.16}'.format(name_string))

======| Phil |==  # Result
====| Phil |==== # What I want

You can define a function that will return your desired output: 您可以定义一个将返回所需输出的函数:

def heading(text):
    return '{0:=^16}'.format(text)
heading(name_choice)

Please note that if one of the names in the list is longer than 16 characters, this function will return the entire name, without = signs. 请注意,如果列表中的某个名称长度超过16个字符,则此函数将返回整个名称,不带=符号。

您应该更改print('{0:.16}'.format(name_string))print('{0:16}'.format(name_string)) ,然后它将起作用。

Adding | {0} | 添加| {0} | | {0} | to the formatting in simon.sim's answer produces the OP's desired ouput shown in the question: simon.sim中的格式化答案产生了OP在问题中显示的所需输出:

import random

def extra_format(text):
    return '{0:=^16}'.format(text)

name_list = ['Joe','Phil','Frank','Daniel']
name_choice = random.choice(name_list)
print(extra_format('| {0} |'.format(name_choice))) # ====| Phil |==== # What I want

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM