1

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.

nicael
  • 18,550
  • 13
  • 57
  • 90
hkchakladar
  • 749
  • 1
  • 7
  • 15
  • 1
    Move the closing parenthesis to the end of the last line. Voting to close as typo. – Wooble Apr 05 '14 at 14:57
  • @Wooble I disagree. I don't think it should be closed as the user was not 'hey, I am getting this error' but 'how can I do this?' The code he posted was just what he had tried so far, which is a good thing to post. – anon582847382 Apr 05 '14 at 15:06
  • @Wooble, thanks for replying to my question, Really this works just moving the parenthesis. Also alex thorton, your code also works by using .format. Which one should I use ? – hkchakladar Apr 06 '14 at 09:22
  • @chakladar http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format – anon582847382 Apr 06 '14 at 10:27

3 Answers3

2

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

p1 = input('Welcome {0} > Enter your no:'.format(p1))
anon582847382
  • 19,907
  • 5
  • 54
  • 57
1

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.

Liam McInroy
  • 4,339
  • 5
  • 32
  • 53
0

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.

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437