python - 如何在 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.
解决方案
使用 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()
推荐阅读
- java - 使用 Spring Boot Actuator 在运行时更改 Camel 日志级别
- python - 迭代并选择列表python的每两个元素
- postgresql - 在 Symfony 项目中应该使用表名“user”吗?
- bash - 如何使用布尔参数调用 bash 函数?
- python - 网格搜索 ValueError:估计器的参数分类器无效
- c# - C# 将数字四舍五入为 double 的任意数字
- flutter - 尝试从 API 获取数据 - 基数 10 数无效
- python - 如何将字符串列表转换为单个分隔字符串?
- django - Django - __str__ 返回非字符串(类型元组)
- asp.net-mvc - 如何将模型中的两个类的上下文传递到一个视图而不会出现此错误?