首页 > 解决方案 > 为了使最终输出的单词以大写字母开头,我应该将 .title 函数放在哪里?

问题描述

我知道这可能是一个简单的问题,但作为一个初学者,我想我会问。我创建了一个简单的 Python 脚本来通过终端运行,在被问到三个问题后,用户将得到一个包含所有内容的输出。我想通过将所有回答的单词大写来补充这一点,我知道我可以使用.title 功能,但我不知道把它放在哪里。任何帮助将非常感激。

#ask user for age
name = input('What is your name?: ')
print(name)
#ask user age
age = input('How old are you?: ')
print(age)
#ask user for city
city = input('What city were you born in?: ')
print(city)
#ask user what they enjoy
hobby = input('What do you enjoy doing in your spare time?: ')
print(hobby)
#create output text
string = 'Your name is {} and you are {} years old. you were born in      {} and you enjoy {}'
output = string.format(name, age, city, hobby)

#print output to screen
print(output)

标签: pythoninput

解决方案


你将把它放在这一行:

output = string.format(name.title(), age.title(), city.title(), hobby.title())

这非常简单,因为这是您添加到最终输出中的内容。

您也可以在要求输入后直接添加它,如下所示:

my_name = input('Enter your name:').title()

推荐阅读