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)
这篇关于如何仅将列表中每个字符串的标题大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何仅将列表中每个字符串的标题大写?
基础教程推荐
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- matplotlib 设置 yaxis 标签大小 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
