How to capitalize only the title of each string in the list?(如何仅将列表中每个字符串的标题大写?)
问题描述
全部问题:编写一个函数,将字符串列表作为参数,并返回一个列表,其中包含每个大写为标题的字符串.也就是说,如果输入参数是 ["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)
这篇关于如何仅将列表中每个字符串的标题大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何仅将列表中每个字符串的标题大写?


基础教程推荐
- 包装空间模型 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 求两个直方图的卷积 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01