Andrew Parker
Andrew Parker

Reputation: 59

Python treats "is" to pluralize string literal

Python version 3.4.3

Python converting string literal to plural. I cannot figure out how to solve this.

When I enter:

>>> x = ("The number % is incorrect" % 8)
>>> x
'The number  8s incorrect'

When I try to escape "is" I get an error.

>>> x = ("The number % \is incorrect" % 8)
ValueError: unsupported format character '\' (0x5c) at index 13

Upvotes: 0

Views: 191

Answers (3)

turkus
turkus

Reputation: 4893

Just use format function instead:

x = "The number {} is incorrect".format(8)

Upvotes: 9

Dimitris Fasarakis Hilliard
Dimitris Fasarakis Hilliard

Reputation: 160437

The string:

'the number % is incorrect' % 8

is actually interpreted as:

'the number [% i]s incorrect' % 8
            # ^ conversion specifier 

and according to the docs on formatting, the specifier i is going to get substituted by the integer 8.

This can easily be mediated by actually providing the specifier right after % as in:

'the number %i is incorrect' % 8

Upvotes: 3

perfect5th
perfect5th

Reputation: 2062

Try 'the number %d is incorrect' % 8

The problem is that python is reading your % (with the space, thanks, Ashwini) , and thinking that is your format character.

Upvotes: 6

Related Questions