简体   繁体   English

Python 3:将字符串添加到列表中的 OBJECTS

[英]Python 3: Add string to OBJECTS within a list

I am sure it is a very trivial question but I can not seem to find anything online, perhaps because I am not using the right terminology..我确信这是一个非常微不足道的问题,但我似乎在网上找不到任何东西,也许是因为我没有使用正确的术语。

I have a list that looks like so:我有一个看起来像这样的列表:

list = ["abc",
        "ded"]

I know how to append elements to this list, how to add elements to the beginning, etc. What I need to do is to add a string (more specifically an asterisk (*)) before and after each object in this list.我知道如何将元素添加到此列表中,如何将元素添加到开头等。我需要做的是在此列表中的每个对象之前和之后添加一个字符串(更具体地说是一个星号 (*))。 So it should look like:所以它应该看起来像:

list = ["*abc*",
        "*ded*"]

I have tried:我试过了:

asterisk = '*'
list = [asterisk] + list[0]
list = asterisk + List[0]
list = ['*'] + list[0]
list = * + list[0]

asterisk = list(asterisk)
list = [asterisk] + list[0]

and I always get:我总是得到:

TypeError: can only concatenate list (not "str") to list类型错误:只能将列表(不是“str”)连接到列表

Then of course there is the problem with adding it before and after each of the objects in the list.那么在列表中的每个对象之前和之后添加它当然存在问题。

Any help will be appreciated.任何帮助将不胜感激。

Just string interpolate it in as follows:只需将其字符串插入如下:

[f'*{s}*' for s in ["abc","ded"]]

Output输出

['*abc*', '*ded*']

Note this is for Python 3.6+ only.请注意,这仅适用于 Python 3.6+。

For your list you use this beautiful syntax, called "list comprehension":对于您的列表,您可以使用这种漂亮的语法,称为“列表理解”:

lst = ['abc', 'ded']
lst = ['*'+s+'*' for s in lst]
print(lst)

This would get you:这会让你:

['*abc*', '*ded*']

Have you tried using a list comprehension to adjust您是否尝试过使用列表理解来调整

[('*'+i) for i in asterix]

you can give it a name just for good measure so that you can call it later你可以给它起个名字只是为了更好的衡量,以便你以后可以调用它

You can join the asterisks with each word每个单词都可以加入星号

asterisked = [w.join('**') for w in lst]

The trick here is to remember that strings are iterables, so you can pass a string that contains two asterisks to the word's join method to let it prepend the word with the first asterisk and append the second one这里的技巧是记住字符串是可迭代的,因此您可以将包含两个星号的字符串传递给单词的 join 方法,让它在单词前面加上第一个星号并附加第二个

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

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