美文网首页
字符串拼接

字符串拼接

作者: manbug | 来源:发表于2017-10-11 11:30 被阅读0次

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)

相关文章

  • R 包学习 - stringr()

    stringr: R 语言字符串处理包 字符串拼接函数str_c: 字符串拼接。str_join: 字符串拼接,同...

  • Swift5.0 字符串(String)详解

    1.字符串拼接 + 拼接 \() 拼接 2.字符串是否为空判断 3.字符串长度 4.字符串比较 == > < 5....

  • 字符串

    遍历 拼接 字符串拼接格式化 字符串的截取

  • Python 字符串详解

    字符串替换 字符串拼接 1.两个字符串拼接 2.打印拼接 字符串按照字符切割 字符串比较 字符串长度 字符串是否包...

  • 字符串api

    字符串 增 concat() //拼接任意字符串,并返回拼接后的字符串 加号 ➕ 同上 字符串 ...

  • 批量根据id修改字段

    update tableName set 字段名 = concat(id,'拼接字符串','拼接字符串');

  • 142字符串的高效处理

    1、字符串的拼接 2、StringBuilder类(字符串构建器) 使用StringBuilder来拼接字符串: ...

  • go语言string之Buffer与Builder

    操作字符串离不开字符串的拼接,但是Go中string是只读类型,大量字符串的拼接会造成性能问题。 字符串拼接的方式...

  • 字符串操作

    字符串操作 拼接 截取 长度 相等 包含 替换 去除开头末尾字符串 字符串分割 字符串拼接

  • ES6之字符串的扩展(上)

    模板字符串 在传统的拼接字符串中,使用的是‘+’进行拼接: 可以看出用+进行拼接字符串比较繁琐,尤其是当字符串特别...

网友评论

      本文标题:字符串拼接

      本文链接:https://www.haomeiwen.com/subject/ahoiyxtx.html