How can I escape the format string?

前端 未结 3 1022
-上瘾入骨i
-上瘾入骨i 2020-12-19 08:46

Is it possible to use Python\'s str.format(key=value) syntax to replace only certain keys.

Consider this example:

my_string = \'Hello {n         


        
3条回答
  •  刺人心
    刺人心 (楼主)
    2020-12-19 09:30

    A bit of a simpler workaround which I use:

    my_string = 'Hello {name}, my name is {my_name}!'
    
    to_replace = {
        "search_for" : "replace_with",
        "name" : "minerz029",
    }
    
    for search_str in to_replace:
        my_string = my_string.replace('{' + search_str + '}', to_replace[search_str])
    
    print(my_string)
    

    This can be expanded easily with more keys in the to_replace dict and wont complain even if the search string doesn't exist. It could probably be improved to offer more of .format()'s features, but it was enough for me.

提交回复
热议问题