字符串拼接

update:2018-07-11

python3.6版本以后新出了一种字符串拼接方式

name = "manbug"
msg = "hello"
IN:  f"{msg} aaaaa, {name}"
OUT: 'hello aaaaa, manbug'

如果有括号
IN:  f"{msg} aaaaa, {name}, {{'a':1, 'b': 2, 'c': {name}}}"
OUT: "hello aaaaa, manbug, {'a':1, 'b': 2, 'c': manbug}"

1. format

1. "Look, {} seems like {} {}.".format("he", "a", "dog")
2. "Look, {0} seems like {2} {1}.".format("he", "dog", "a")
3. "Look, {who} seems like {amount} {what}.".format(who="he", amount="a", what="dog")
4. di = {
    "who": "he",
    "amount": "a",
    "what": "dog"
}
"Look, {who} seems like {amount} {what}.".format(**di)
5. "{x} mountain {x} sea".format(x="people")

2. %

1. "Look, %s seems like %s %s." % ("he", "a", "dog")
2. "Look, %(who)s seems like %(amount)s %(what)s." % (who="he", amount="a", what="dog")
3. di = {
    "who": "he",
    "amount": "a",
    "what": "dog"
}
"Look, %(who)s seems like %(amount)s %(what)s." % di
4. "%(x)s mountain %(x)s sea" % (x="people")

3.Jinja2

当拼接的字符串中有"{ }"会干扰format的使用
同理,有"%"会干扰%s的使用
此时可以用Jinja2

from jinja2 import Template
template = Template("""{
    "a": "{{value_a}}",
    "b": {
        "This is {{value_b}}."
    }
}
""")
di = {
    "value_a": "aaaa",
    "value_b": "bbbb"
}
s = template.render(value_a="aaaa", value_b="bbbb")
or
s = template.render(di)
or
s = template.render(**di)

你可能感兴趣的:(字符串拼接)