问题
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