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

时间:2015-04-06 02:30:29

标签: python format

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

我写了这个程序。问题是,如果我输入["apple pie", "brownies","dulce de leche"],则会返回['Apple Pie', ' Brownies', 'Dulce De Leche'] 正如问题所示,每个字符串都必须用引号打印出来,逗号后面没有空格。 请帮助!

这是我的计划:

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()

4 个答案:

答案 0 :(得分:1)

与我之前的回答一样,您只需要使用","加入列表,然后您需要在开头和结尾添加[""]

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 '["' + '","'.join(r)+ '"]'

def main():
  y = Strings()
  x = Capitalize(y)
  print(x)

main()

答案 1 :(得分:0)

不确定为什么有人会这样做,但是你去了:

s = "["
for i in x:
    s += '"' + i + '",'
print s + "]"

答案 2 :(得分:0)

def Capitalize(parameter):
    return ["\""+i.strip().strip("\"").title()+"\"" for i in s[1:-1].split(",")]

title = Capitalize(y)
print "[" + ",".join(title) + "]"

答案 3 :(得分:0)

如果列表是作为合法的python列表[...]输入的,那么你可以使用json模块在python对象(即列表)中转换此字符串,然后在标题字符串后再返回{ {1}}可让您控制分隔符,例如:

json.dumps()