3

I have a string that contains a % that I ALSO want to use %s to replace a section of that string with a variable. Something like

name = 'john'
string = 'hello %s! You owe 10%.' % (name)

But when I run it, I get

not enough arguments for format string

I'm pretty sure that means that python thinks I'm trying to insert more than 1 variable into the string but only included the one. How do I overcome this? Thanks!

Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
kroe761
  • 3,296
  • 9
  • 52
  • 81

2 Answers2

9

You can use a % in your string using this syntax, by escaping it with another %:

>>> name = 'John'
>>> string = 'hello %s! You owe 10%%.' % (name)
>>> string
'hello John! You owe 10%.'

More about: String Formatting Operations - Python 2.x documentation


As @Burhan added after my post, you can bypass this problem by using the format syntax recommended by Python 3:
>>> name = 'John'
>>> string = 'hello {}! You owe 10%'.format(name)
>>> string
'Hello John! You owe 10%'
# Another way, with naming for more readibility
>>> string = 'hello {name}! You owe 10%.'.format(name=name)
>>> str
'hello John! You owe 10%.'
Maxime Lorant
  • 34,607
  • 19
  • 87
  • 97
  • 1
    Thanks! I didn't know I could escape with a percent, I thought I had to use \ (which didn't work). If I may, is there a reason that \ didn't work and % did? Thanks! – kroe761 Jan 07 '14 at 17:09
  • @kroe761 because of the specification for format strings ... ill see if i can find the link but I think its just on the main python docs page about formaT strings (http://docs.python.org/2/library/stdtypes.html#string-formatting last item under conventions) – Joran Beasley Jan 07 '14 at 17:12
0

In addition to what Maxime posted, you can also do this:

>> name = 'john'
>>> str = 'Hello {}! You owe 10%'.format(name)
>>> str
'Hello john! You owe 10%'
Burhan Khalid
  • 169,990
  • 18
  • 245
  • 284