string concatenate

Lie Ryan lie.1296 at gmail.com
Wed Oct 1 14:10:55 EDT 2008


On Wed, 01 Oct 2008 09:41:57 -0700, sandric ionut wrote:

> Hi:
> 
> I have the following situation:
>     nameAll = []
Here you defined nameAll as a list

>     for i in range(1,10,1):
That range is superfluous, you could write this instead[1]:
for i in range(10):

>         n = "name" + str([i])

in this, you're converting a list into a string. If i was 2, the 
conversion result into: 'name' + '[2]'

>         nameAll += n
Here you're appending n into the list nameAll. Python's string behaves 
like a list, that it is iterable, so list accepts it.

>     print nameAll

your code should be:
listAll = []
for i in range(1, 11):
    n = "name" + str(i)
    listAll.append(n)
print ' '.join(listAll)

or using list comprehension and string interpolation:
print ' '.join('name%s' % i for i in range(1, 11))

[1] Note that range(10) starts with 0, and produces a list of 10 numbers. 
If, like in your expected result, you want name1 till name10, you'll need 
range(1, 11) because range is half-open, it includes 1, but not 11. This 
behavior has some unique property that simplifies many things, although 
it do takes some time to get used to.




More information about the Python-list mailing list