在下面我有一个数组,其中每个元素都应该在开头添加一个字符串而不是追加,我该怎么做
a=["Hi","Sam","How"]
I want to add "Hello" at the start of each element so that the output will be
Output:
a=["HelloHi","HelloSam","HelloHow"]
在下面我有一个数组,其中每个元素都应该在开头添加一个字符串而不是追加,我该怎么做
a=["Hi","Sam","How"]
I want to add "Hello" at the start of each element so that the output will be
Output:
a=["HelloHi","HelloSam","HelloHow"]
这适用于字符串列表:
a = ['Hello'+b for b in a]
这也适用于其他对象(使用它们的字符串表示):
a = ['Hello{}'.format(b) for b in a]
例子:
a = ["Hi", "Sam", "How", 1, {'x': 123}, None]
a = ['Hello{}'.format(b) for b in a]
# ['HelloHi', 'HelloSam', 'HelloHow', 'Hello1', "Hello{'x': 123}", 'HelloNone']
或者您可以使用map
:
map('Hello{0}'.format,a)
a=["Hi","Sam","How"]
a = ["hello" + x for x in a]
print a
另外的选择:
>>> def say_hello(foo):
... return 'Hello{}'.format(foo)
...
>>> map(say_hello,['hi','there'])
['Hellohi', 'Hellothere']