How can I selectively escape percent (%) in Python strings?
Become part of the top 3% of the developers by applying to Toptal https://topt.al/25cXVn
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind
--
Chapters
00:00 Question
00:31 Accepted answer (Score 728)
00:43 Answer 2 (Score 61)
01:09 Answer 3 (Score 47)
01:21 Answer 4 (Score 10)
02:06 Thank you
--
Full question
https://stackoverflow.com/questions/1067...
Answer 1 links:
[PEP 3101]: http://www.python.org/dev/peps/pep-3101/
Answer 3 links:
[documentation]: https://docs.python.org/2/library/stdtyp...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #escaping #python27
#avk47
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Peaceful Mind
--
Chapters
00:00 Question
00:31 Accepted answer (Score 728)
00:43 Answer 2 (Score 61)
01:09 Answer 3 (Score 47)
01:21 Answer 4 (Score 10)
02:06 Thank you
--
Full question
https://stackoverflow.com/questions/1067...
Answer 1 links:
[PEP 3101]: http://www.python.org/dev/peps/pep-3101/
Answer 3 links:
[documentation]: https://docs.python.org/2/library/stdtyp...
--
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.