問題描述
全部問題:編寫一個函數,將字符串列表作為參數,并返回一個列表,其中包含每個大寫為標題的字符串.也就是說,如果輸入參數是 ["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)
這篇關于如何僅將列表中每個字符串的標題大寫?的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!