Python: how to escape “%s”

空扰寡人 提交于 2020-01-25 02:47:08

问题


I'm trying to make a string that includes a "%s" with no formatting

For example, I want this:

#I want to make mystring = "x %s"

first_value = "x"
mystring = "%s %s" % first_value

So, I want to format the first %s, but leave the second %s in the string.. Of course the above code gives me a "TypeError:not enough arguments for format string"

Is there a way to achieve this in one line?

Thanks


EDIT: I know I can do

mystring = "%s %s" % (first_value, "%s")

but this kind of looks ugly.. Is there a better way?


回答1:


You can escape a % character in a format string by doubling it:

>>> "%s %%s" % "x"
"x %s"



回答2:


You can assign your string like this:

mystring = "{} %s".format(first_value)

If you are working with Python 2.6 or earlier, you will need to add an integer index in the curly braces:

mystring = "{0} %s".format(first_value)

A nice thing about this method is that first_value can change types later and you don't have to adjust your definition of mystring because .format() can take different types, and you don't need first_value's type to match a format string.

I also think it looks cleaner than escaping percent signs, but I know that is very subjective.




回答3:


Try concatenating instead:

mystring = ("%s " % first_value) + "%s"

outputs x %s




回答4:


Prepend %s with a % to escape it:

mystring = "%s %%s" % first_value
'x %s'



回答5:


You can escape the first '%' by leading it with a second:

 print "%%s%s" % 'hello world'

%shello world



来源:https://stackoverflow.com/questions/26393895/python-how-to-escape-s

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!