Changing formatting string from % to alternate character?
In python 2.6, is there a way to specify an alternate character other than % for string formatting operations? Or is the % char hardcoded in the python interpreter?
For example, to generate a string that looks like this:
param1%02param2%03param3...
I currently have t开发者_JAVA百科o do this:
str = "%s%%02%s%%03%s" % (param1, param2, param3)
What I'd like to be able to do is substitute, say, ^ for % and be able to do:
str = "^s%02^s%03^s" ^ (param1, param2, param3)
which IMO is far more readable.
You can use the new str.format
method. It offers more formatting options and is more readable.
>>> '{0}%02{1}%03{2}'.format('a', 'b', 'c')
'a%02b%03c'
>>> '{param1} is also {param2}'.format(param1='foo', param2='bar')
'foo is also bar'
>>> '{0[name]} is {0[age]} years old'.format({'name': 'Bob', 'age': 42})
'Bob is 42 years old'
For more information, check the documentation: Format string syntax
%
is hardcoded. You could, however, do something like...
your_str = ("%s^02%s^03%s" % (param1, param2, param3)).replace("^", "%")
or
your_str = ''.join([param1, '%02', param2, '%03', param3])
I completely agree with JBernardo's answer, however, for completeness I just wanted to point out that it is indeed possible to adapt the language to the questioner's needs. That involves deriving a class from str
and overriding its ^
operator:
class yourstr(str):
def __xor__(self, tuple):
return self.replace("%", "%%").replace("^", "%") % tuple
Then you can do something like:
>>> param1 = "foo"
>>> param2 = "bar"
>>> param3 = "quux"
>>> yourstr("^s%02^s%03^s") ^ (param1, param2, param3)
'foo%02bar%03quux'
I wouldn't recommend doing that in the general case, though, since it makes the code harder to read and maintain.
You can't - its not even hard-coded in python, its hard-coded somewhere in libc (a level below the interpreter). You could write a function that will the string with the ^
and convert them to %
and take the existing %
and convert them to %%
and then pass it to formatting.
精彩评论