Question

I want to take input as string as raw_input and want to use this value in another line for taking the input in python. My code is below:

p1 = raw_input('Enter the name of Player 1 :')
p2 = raw_input('Enter the name of Player 2 :')


p1 = input('Welcome %s > Enter your no:') % p1

Here in place of %s I want to put the value of p1.

Thanks in advance.

Was it helpful?

Solution

You can do (the vast majority will agree that this is the best way):

p1 = input('Welcome {0} > Enter your no:'.format(p1))

OTHER TIPS

Try

input("Welcome " + p1 + "> Enter your no:")

It concatenates the value of p1 to the input string

Also see here

input("Welcome {0}, {1} > Enter your no".format(p1, p2)) #you can have multiple values

EDIT

Note that using + is discouraged.

This doesn't work because Python interprets

p1 = input('Welcome %s > Enter your no:') % p1

As:

  1. Get input, using the prompt 'Welcome %s > Enter your no:';
  2. Try to insert p1 into the text returned by input, which will cause a TypeError unless the user's number includes '%s'; and
  3. Assign the result of that formatting back to p1.

The minimal fix here is:

p1 = input('Welcome %s > Enter your no:' % p1)

which will carry out the % formatting before using the string as a prompt, but I agree with the other answers that str.format is the preferred method for this.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top