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)
这篇关于如何仅将列表中每个字符串的标题大写?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:如何仅将列表中每个字符串的标题大写?
基础教程推荐
- Dask.array.套用_沿_轴:由于额外的元素([1]),使用dask.array的每一行作为另一个函数的输入失败 2022-01-01
- 在 Python 中,如果我在一个“with"中返回.块,文件还会关闭吗? 2022-01-01
- 如何在海运重新绘制中自定义标题和y标签 2022-01-01
- Python kivy 入口点 inflateRest2 无法定位 libpng16-16.dll 2022-01-01
- 线程时出现 msgbox 错误,GUI 块 2022-01-01
- 何时使用 os.name、sys.platform 或 platform.system? 2022-01-01
- 用于分类数据的跳跃记号标签 2022-01-01
- 筛选NumPy数组 2022-01-01
- 如何让 python 脚本监听来自另一个脚本的输入 2022-01-01
- 使用PyInstaller后在Windows中打开可执行文件时出错 2022-01-01