次の配列では、要素ごとに文字列を最初に追加し、追加する必要はありません。これを行うにはどうすればよいですか?
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']
a=["Hi","Sam","How"]
a = ["hello" + x for x in a]
print a
または使用できますmap
:
map('Hello{0}'.format,a)
別のオプション:
>>> def say_hello(foo):
... return 'Hello{}'.format(foo)
...
>>> map(say_hello,['hi','there'])
['Hellohi', 'Hellothere']