python - Is there a way to only replace part of format string? -
example:
format_string = "http://somedomain.com/%s/%d" format_string %= ('somestring', %d) print(format_string) >>> http://somedomain.com/somestring/%d
is there way this?
the string interpolation requires have 1 item each "conversion specification" in string. however, can escape "conversion specification" % ...
format_string = 'http://somedomain.com/%s/%%d' print(format_string % 'foo')
of course, complete "hack" (that work if you're trying replace %s
) put conversion string in place of original one...:
format_string = '%s%s' print(format_string % ('foo', '%s'))
again, doesn't work in scenario...
other options use .format
style string formatting and write own formatter. note, isn't faint @ heart -- here's basic example1:
import string class myformat(string.formatter): def vformat(self, format_string, args, kwargs): out_lst = [] iargs = iter(args) tup in self.parse(format_string): literal_text, _, format_spec, _ = tup if literal_text: out_lst.append(literal_text) if format_spec: try: out_lst.append(format_spec % next(iargs)) except stopiteration: out_lst.append('{:' + format_spec + '}') return ''.join(out_lst) print(myformat().format('foo {:%s} {:%d}', 'a', 10)) # foo 10 print(myformat().format('foo {:%s} {:%d}', 'a')) # foo {:%d}
1this first attempt ever write 1 of these ... it's possible can done more cleanly , i'll happily accept improvements...
Comments
Post a Comment