如何在Python中转换大写名称?

时间:2019-11-28 07:06:52

标签: python

我想在print("\nThank you, " + name + ".")中有个名字,我可以在其中输入任何大小写的小写字母。我尝试在结尾处以及在.lower()之后同时添加.upper()name,但是没有用。有什么办法吗?下面是示例。

def welcomeGame():
   name=input("Hello! Welcome to my game. What is your first name? ")

   while True:
      if name.istitle() and name.isalpha():
         break

      print("\nI'm sorry " + name + ", names are only allowed to contain letters, and with the first capitalized letter of your name.")
      name=input("Please re-enter your name: ")

   print("\nThank you, " + name + ".")
   print("\nYou will start off with 0 points, let's play!\n")  
welcomeGame()

我希望它看起来如何。

Hello! Welcome to my game. What is your first name? bEn
I'm sorry bEn, names are only allowed to contain letters, and with the first capitalized letter of your name.
Please re-enter your name: bEN

# the actual output after it asks to re-enter your name:
I'm sorry bEN, names are only allowed to contain letters, and with the first capitalized letter of your name. 
Please re-enter your name.

# how I actually want the output to look like after it asks to re-enter your name:
Thank you, Ben.

1 个答案:

答案 0 :(得分:1)

使用title()函数。

def welcomeGame():
   name=input("Hello! Welcome to my game. What is your first name? ")

   while True:
      if name.istitle() and name.isalpha():
         break

      print("\nI'm sorry " + name + ", names are only allowed to contain letters, and 
with the first capitalized letter of your name.")
      name=input("Please re-enter your name: ").title()

   print("\nThank you, " + name + ".")
   print("\nYou will start off with 0 points, let's play!\n")  
welcomeGame()