zoukankan      html  css  js  c++  java
  • Python字符串拼接的七种方法

    在处理日志和HTTP请求响应等需要对数据进行格式化的时候我们都会用到字符串拼接,相信你也有自己喜欢的方式,今天我们就来总结一下。

    直接通过“+”拼接

    >>> 'Hello' + ' ' + 'World' + '!'
    'Hello World!'
    

    通过str.join()方法拼接

    >>> strlist = ['Hello', ' ', 'World', '!']
    >>> ''.join(strlist)
    'Hello World!'
    

    通过str.format()方法拼接【个人喜欢这种方式】

    >>> '{} {}!'.format('Hello', 'World')
    'Hello World!'
    

    通过“%”操作符拼接

    >>> '%s %s!' % ('Hello', 'World')
    'Hello World!'
    

    通过“()”多行拼接

    >>> (
    ...     'Hello'
    ...     ' '
    ...     'World'
    ...     '!'
    ... )
    'Hello World!'
    

    通过string模块的Template对象拼接

    >>> from string import Template
    >>> s = Template('${s1} ${s2} ${s3}!') 
    >>> s.safe_substitute(s1='Hello',s2='World')
    'Hello World ${s3}!'
    

    通过f表达式拼接(支持传入方法)

    >>> s1 = 'Hello'
    >>> s2 = 'World'
    >>> f'{s1} {s2}!'
    'Hello World!'
    

    执行方法:

    >>> def hello():
    ...     print("hello py")
    ...
    >>> a=f'{hello()}'
    hello py
    
  • 相关阅读:
    OpenGL模板 Mac Cmake OpenGL(Glut) Template
    CodeForces 277A Learning Languages (并检查集合)
    Linux netstat订购具体解释
    POJ 1936 All in All
    他的第一个NDK的Demo
    [ACM] POJ 2418 Hardwood Species (Trie树或map)
    Swift
    Swift
    Swift
    Swift
  • 原文地址:https://www.cnblogs.com/phyger/p/13737303.html
Copyright © 2011-2022 走看看