如何仅将列表中每个字符串的标题大写?
问题描述
全部问题:编写一个函数,将字符串列表作为参数,并返回一个列表,其中包含每个大写为标题的字符串.也就是说,如果输入参数是 ["apple pie", "brownies","chocolate","dulce de leche","eclairs"]
,你的函数应该返回 ["Apple馅饼"、布朗尼"、巧克力"、德莱切"、泡芙"]
.
WHOLE QUESTION: Write a function that takes as a parameter a list of strings and returns a list containing the each string capitalized as a title. That is, if the input parameter is ["apple pie", "brownies","chocolate","dulce de leche","eclairs"]
, your function should return ["Apple Pie", "Brownies","Chocolate","Dulce De Leche","Eclairs"]
.
我的程序(更新):
我想我的程序现在正在运行!问题是当我输入: ["apple pie"]
它正在返回: ['"Apple Pie"']
I THINK I GOT MY PROGRAM RUNNING NOW! The problem is when I enter: ["apple pie"]
it is returning: ['"Apple Pie"']
def Strings():
s = []
strings = input("Please enter a list of strings: ").title()
List = strings.replace('"','').replace('[','').replace(']','').split(",")
List = List + s
return List
def Capitalize(parameter):
r = []
for i in parameter:
r.append(i)
return r
def main():
y = Strings()
x = Capitalize(y)
print(x)
main()
我收到一个错误 AttributeError: 'list' object has no attribute 'title'
请帮忙!
I am getting an error AttributeError: 'list' object has no attribute 'title'
Please help!
解决方案
只需遍历名称列表,然后对于每个名称,仅通过指定首字母的索引号来更改首字母的大小写.然后将返回的结果与剩余的字符相加,最后将新名称附加到已经创建的空列表中.
Just iterate over the name list and then for each name, change the case of first letter only by specifying the index number of first letter. And then add the returned result with the remaining chars then finally append the new name to the already created empty list.
def Strings():
strings = input("Please enter a list of strings: ")
List = strings.replace('"','').replace('[','').replace(']','').split(",")
return List
def Capitalize(parameter):
r = []
for i in parameter:
m = ""
for j in i.split():
m += j[0].upper() + j[1:] + " "
r.append(m.rstrip())
return r
def main():
y = Strings()
x = Capitalize(y)
print(x)
main()
或
import re
strings = input("Please enter a list of strings: ")
List = [re.sub(r'^[A-Za-z]|(?<=s)[A-Za-z]', lambda m: m.group().upper(), name) for name in strings.replace('"','').replace('[','').replace(']','').split(",")]
print(List)
相关文章