python将字符串添加到数组中每个元素的开头

时间:2013-01-09 10:14:41

标签: python

在下面我有一个数组,其中每个元素应该在开始时添加一个字符串而不是追加,我该怎么做

 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"]

4 个答案:

答案 0 :(得分:4)

这适用于字符串列表:

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']

答案 1 :(得分:1)

a=["Hi","Sam","How"]
a = ["hello" + x for x in a]
print a

答案 2 :(得分:1)

或者您可以使用map

map('Hello{0}'.format,a)

答案 3 :(得分:0)

另一种选择:

>>> def say_hello(foo):
...   return 'Hello{}'.format(foo)
... 
>>> map(say_hello,['hi','there'])
['Hellohi', 'Hellothere']