Python中如何将类中字符串属性首字母大写输出?
解决餐厅名称首字母大写的问题
你可以利用Python字符串的title()方法,它会把每个单词的首字母转为大写、其余字母转为小写,刚好匹配你的需求。下面提供两种实现方式:
方式一:初始化时统一处理名称(推荐)
在类的__init__方法中直接格式化餐厅名称,后续所有用到名称的方法都无需重复处理:
class Restaurant: def __init__ (self, restaurant_name, cuisine_type): # 初始化时将名称转为首字母大写格式 self.name = restaurant_name.title() self.type = cuisine_type def describe_restaurant(self): print(f"This restaurants name is: '{self.name}' and serves {self.type}") def restaurant_open(self): print(f"'{self.name}' is currently open") res1 = Restaurant('pho hung','vietnamese pho') res1.describe_restaurant() res2 = Restaurant('macdonalds','american fast') res2.describe_restaurant() res2.restaurant_open()
方式二:仅在输出时临时处理
如果不想修改原始存储的名称,可在输出方法中单独处理:
class Restaurant: def __init__ (self, restaurant_name, cuisine_type): self.name = restaurant_name self.type = cuisine_type def describe_restaurant(self): # 输出时调用title()格式化名称 print(f"This restaurants name is: '{self.name.title()}' and serves {self.type}") def restaurant_open(self): # 输出时调用title()格式化名称 print(f"'{self.name.title()}' is currently open") res1 = Restaurant('pho hung','vietnamese pho') res1.describe_restaurant() res2 = Restaurant('macdonalds','american fast') res2.describe_restaurant() res2.restaurant_open()
两种方式运行后都会输出符合要求的结果:
This restaurants name is: 'Pho Hung' and serves vietnamese pho This restaurants name is: 'Macdonalds' and serves american fast 'Macdonalds' is currently open
内容的提问来源于stack exchange,提问作者Minh Tee
相关产品推荐
相关产品推荐

