首页 > 解决方案 > 如何在 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.

标签: python

解决方案


使用 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()

推荐阅读