Gillian
Gillian

Reputation: 13

Concatenating variables and incremental numbers in python

I have a list of words, and I want to have a loop that picks a random word from it and concatenates the next number onto that word.

So far I have

import random
wordList = ['some', 'choice', 'words', 'here']
for x in range(0, 10):
    word = random.choice(wordList)
    print word %(x)

which throws the error "TypeError: not all arguments converted during string formatting"

I am trying to follow the format of

for x in range(0, 10):
    print "number%d" %(x)

which succesfully prints

number0 number1 number2 number3 number4 number5 number6 number7 number8 number9

I assume my problem is with the formatting of the string variable, but I can't figure out how to correct it.

Upvotes: 1

Views: 233

Answers (2)

victor
victor

Reputation: 1644

EDIT: Used a more, in my opinion, readable answer based on @Alan Leuthard's comment.

You need to specify where to format inside the string.

for x in range(0, 10):
    word = random.choice(wordList)
    print "%s%d" %(word, x)

Or if you are looking for a oneliner,

for x in range(0, 10):
    print "%s%d" %(random.choice(wordList), x)

If you are using Python 2.7+ or 3.x, it is far easier to use braces instead.

for x in range(0, 10):
    print("{}{}".format(random.choice(wordList), x))

But if you want to use braces in Python 2.6

for x in range(0, 10):
    print("{0}{1}".format(random.choice(wordList), x))

Upvotes: 3

rma
rma

Reputation: 1958

This means that not all the arguments are being converted in the string. It's because you forgot to add a "%d" to the end of the string. This should work

   In [29]: import random
        ...: wordList = ['some', 'choice', 'words', 'here']
        ...: for x in range(0, 10):
        ...:     word = random.choice(wordList) + "%d"
        ...:     print word %(x)
        ...:
here0
here1
some2
words3
words4
some5
here6
here7
words8
words9

Upvotes: 1

Related Questions