简体   繁体   English

如何大写列表中字符串的某些索引?

[英]How to capitalize certain index of a string in a list?

I have a list containing multiple stings. 我有一个包含多个st的列表。 The strings all start with a "*" and then a "[" with a space in between. 字符串均以“ *”开头,然后以“ [”开头,中间有空格。 Like this: 像这样:

* [context......

Now i would like to capitalize "c". 现在我想大写“ c”。 In other words, i would like to capitalize the first letter of all the strings. 换句话说,我想将所有字符串的首字母大写。 But since i use symbols first. 但是因为我先使用符号。 the Capitalize() function wont work. Capitalize()函数将不起作用。

What i have tried is to capitalize the index like this: 我试过的是大写这样的索引:

list = [i[3].capitalize() for i in list]

The output of this, is just the capitalized letters. 此输出仅是大写字母。 And not the rest of the string. 而不是其余的字符串。

The easiest way is to use .title() which ignores non-alphabetical characters: 最简单的方法是使用.title() ,它会忽略非字母字符:

>>> my_list = ['* [foo]', '* [bar]']
>>> map(lambda s: s.title(), my_list)
['* [Foo]', '* [Bar]']

or using a list comprehension: 或使用列表理解:

>>> [s.title() for s in my_list]
['* [Foo]', '* [Bar]']

If they all start that way, then I think this would do what you want. 如果它们都是以这种方式开始的,那么我认为这将满足您的要求。

list_ = [i[:3] + i[3:].capitalize() for i in list_]

Note that you shouldn't use the built in keyword list as a variable name (it covers over its purpose in the code). 请注意,您不应将内置关键字list用作变量名(它涵盖了代码中的目的)。

TRY:- 尝试:-

list1 = [ "* [context......", "* [context1......" ]

for x in list1:

    print(x[:3] + x[3].capitalize() + x[4:])

OUTPUT:- 输出:-

* [Context......
* [Context1......

Here's an example using upper() instead of capitalize. 这是一个使用upper()而不是大写的示例。 Reference from here 这里参考

test = ['* [context......', '* [bontext......', '* [zontext......']

test = [i[:3] + i[3:4].upper() + i[4:] for i in test]

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM