我被要求为一个使用两个列表的类编写一个程序。一个列表包含 7 个人的姓名(我使用了总统的名字),另一个包含他们的 7 个电话号码。该程序的目标是让用户输入朋友的姓名,然后程序显示该朋友的电话号码。我让程序按照我想要的方式工作,但输出在其中放置了一个我不想要的额外空间。输出如下所示:
Your friend George Washington 's phone number is: 249-451-2869
Run Code Online (Sandbox Code Playgroud)
我想删除“Washington”和“'s”之间的空格,使其读起来更自然。我尝试了不同版本的 strip() 但无法摆脱讨厌的空间。下面是该程序的主要代码:
personName = nameGenerator() #function to allow user to enter name
nameIndex = IsNameInList(personName, Friends) #function that checks the user's input to see if input is #in the name list
print('Your friend',Friends[nameIndex],"\'s phone number is:",Phone_Numbers[nameIndex]) #Friends is name list, Phone_Numbers is numbers list, nameIndex stores the index of the proper name and phone number
Run Code Online (Sandbox Code Playgroud)
print默认情况下在参数之间添加空格;通过sep=''(空字符串)来禁用它。您需要在需要的地方手动添加后退空格,但这是最小的更改:
print('Your friend ', Friends[nameIndex], "\'s phone number is: ", Phone_Numbers[nameIndex], sep='')
Run Code Online (Sandbox Code Playgroud)
或者,只需使用f 字符串(或您喜欢的任何其他字符串格式化技术)在打印前将其格式化为单个字符串:
print(f"Your friend {Friends[nameIndex]}'s phone number is: {Phone_Numbers[nameIndex]}")
Run Code Online (Sandbox Code Playgroud)