1

In the following i have an array where for each element a string should be added at the start and not append ,how can i do this

 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 Answers 4

4

This works for a list of strings:

a = ['Hello'+b for b in a]

and this works for other objects too (uses their strings representation):

a = ['Hello{}'.format(b) for b in a]

Example:

a = ["Hi", "Sam", "How", 1, {'x': 123}, None]
a = ['Hello{}'.format(b) for b in a]
# ['HelloHi', 'HelloSam', 'HelloHow', 'Hello1', "Hello{'x': 123}", 'HelloNone']
Sign up to request clarification or add additional context in comments.

2 Comments

To allow non-string objects using the + operator you can simply add a call to str. str.format is about 15% slower than using the string concatenation(and more than 50% slower than string concatenation without calling str. Even though probably every solution proposed is efficient enough in almost all situations).
One note here: If you want the starting string to be based on an index, you can do the following using enumerate: a = ["Index"+str(idx)+". "+array_element for idx,array_element in enumerate(myArray, 1)]. This will produce something like: Index1. ArrayElement1 Index2. Arrayelement2 and so on.
1
a=["Hi","Sam","How"]
a = ["hello" + x for x in a]
print a

Comments

1

or you can use map:

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

Comments

0

Another option:

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.