如何仅将列表中每个字符串的标题大写?

时间:2015-04-06 00:10:56

标签: python text format

整个问题:编写一个函数,该函数将字符串列表作为参数,并返回一个列表,其中包含大写为标题的每个字符串。也就是说,如果输入参数为["apple pie", "brownies","chocolate","dulce de leche","eclairs"],则您的函数应返回["Apple Pie", "Brownies","Chocolate","Dulce De Leche","Eclairs"]

我的节目(更新):

我认为我现在正在运行我的计划!问题是当我输入时:["apple pie"]它正在返回:['"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' 请帮忙!

2 个答案:

答案 0 :(得分:0)

您正在列表中操作,而不是列表中的元素。

 r.title()

这没有任何意义。

答案 1 :(得分:0)

只需遍历名称列表,然后对每个名称,仅通过指定首字母的索引号来更改第一个字母的大小写。然后使用剩余的字符添加返回的结果,最后将新名称附加到已创建的空列表中。

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)