Skip to main content
 首页 » 编程设计

Python:试图通过在名片上移动外边框来获取用户输入

2024年10月25日10dudu

first_name = input("What is your first name?") 
 
last_name = input("What is your last name?") 
 
phone_number = input("What is your phone #?") 
 
one = ('|') 
two = ('|') 
print('Here is your business card...') 
 
business_card = """ 
+------------------------------------------------+ 
|    |                                           | 
|   -|          %s, %s                           %s 
|  --|          Tribute Liabilities Associate    | 
| ---|          Parasail Capital                 | 
| ---------                                      | 
|  -------      4 Hunger Plaza                   | 
|               STE 1400                         | 
|               District 12, Panem 00012         |  
|                                                | 
| Work: %s  @: champ@parasail.com                %s 
+------------------------------------------------+""" % (first_name, last_name, one , phone_number, two) 
 
 
 
print (business_card) 
 
print('Here is your business card...') 

尝试在不移动边框的情况下在名片上输入名字/姓氏和电话号码。由于名称和/或电话号码产生的空白,它会自动移动边框(向左或向右)....有什么想法吗?

请您参考如下方法:

如果您使用 format() 字符串方法,您可以告诉它在您输入的字符串的两边放置多少空白。

这是 format() 中涉及的迷你语言的文档: https://docs.python.org/2/library/string.html#formatspec

因此,当您输入名称时,您会执行类似 "{:15}".format(name) 的操作,其中 15 是您允许的空格数填充(输入默认为左对齐)。与 "%s"% (name) 相比,这为您提供了更多控制权,并允许更轻松地格式化。

一般来说,format() 文档将提供有关如何动态格式化字符串的大量信息。