How can I selectively escape percent (%) in Python strings?
--------------------------------------------------
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Beneath the City Looping
--
Chapters
00:00 How Can I Selectively Escape Percent (%) In Python Strings?
00:26 Accepted Answer Score 737
00:40 Answer 2 Score 62
01:01 Answer 3 Score 50
01:13 Answer 4 Score 10
01:55 Answer 5 Score 6
02:11 Thank you
--
Full question
https://stackoverflow.com/questions/1067...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #escaping #python27
#avk47
Rise to the top 3% as a developer or hire one of them at Toptal: https://topt.al/25cXVn
--------------------------------------------------
Music by Eric Matyas
https://www.soundimage.org
Track title: Beneath the City Looping
--
Chapters
00:00 How Can I Selectively Escape Percent (%) In Python Strings?
00:26 Accepted Answer Score 737
00:40 Answer 2 Score 62
01:01 Answer 3 Score 50
01:13 Answer 4 Score 10
01:55 Answer 5 Score 6
02:11 Thank you
--
Full question
https://stackoverflow.com/questions/1067...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #escaping #python27
#avk47
ACCEPTED ANSWER
Score 738
>>> test = "have it break."
>>> selectiveEscape = "Print percent %% in sentence and not %s" % test
>>> print selectiveEscape
Print percent % in sentence and not have it break.
ANSWER 2
Score 62
Alternatively, as of Python 2.6, you can use new string formatting (described in PEP 3101):
'Print percent % in sentence and not {0}'.format(test)
which is especially handy as your strings get more complicated.
ANSWER 3
Score 50
try using %% to print % sign .
ANSWER 4
Score 10
You can't selectively escape %, as % always has a special meaning depending on the following character.
In the documentation of Python, at the bottem of the second table in that section, it states:
'%' No argument is converted, results in a '%' character in the result.
Therefore you should use:
selectiveEscape = "Print percent %% in sentence and not %s" % (test, )
(please note the expicit change to tuple as argument to %)
Without knowing about the above, I would have done:
selectiveEscape = "Print percent %s in sentence and not %s" % ('%', test)
with the knowledge you obviously already had.