美文网首页
05 python 中字符串拼接的几种方法

05 python 中字符串拼接的几种方法

作者: 小码码 | 来源:发表于2018-07-02 12:24 被阅读24次

    1 方法一:用‘+’

    示例:

    test_str = 'hello' + ' ' + 'world'
    print(test_str)
    
    输出:hello world
    
    • 优点:简洁方便
    • 缺点:当有多个字符串相加拼接时,执行效率低下。因为字符串是不可变类型,相加以后会生成一个新的字符串,需要重新分配内存。当有多个字符串相加时,每加一次需要重新分配一次内存,多个字符相加需要相加多次,所以需要多次分配内存,从而导致效率低下。
    • 适用场景:少量字符相加的场景

    2 方法二:%s等格式化

    示例:

    tp1 = 'i am %s' % 'alex'  
    tp2='i am %s age %d' % ('alex', 18)    //s对应字符串  d对应int
    tp3='i am %(name)s age %(age)d' % {'name':'alex','age':18}    // 通过key来取值
    
    msg = 'iam %s,my hobby is %s' % ('lll',1)    // s是万能的,对于int同样可用
    print(msg)    // iam lll,my hobby is 1
    
    msg = 'iam %s,my hobby is %s' % ('lll',[1,2])   // s是万能的,对应list同样可用
    print(msg)    // iam lll,my hobby is [1, 2]
    
    msg = 'iam %s,my hobby is %d' % ('lll',[1,2])
    print(msg)     //报错  TypeError: %d format: a number is required, not list
    
    tp = 'percent %f' % 99.231465    //f 对应浮点数
    print(tp)       // percent 99.231465
    
    tp = 'percent %.2f' % 99.231465    //2代表小数位数
    print(tp)       // percent 99.23
    
    tp = 'percent %.2s' % 99.231465   //2代表字符串长度
    print(tp)       // percent 99
    

    3 方法三:format格式化

    tp = 'i am {}, age {}, {}'.format('lucy', 18, 'alex')     //会自动一 一对应
    print(tp)     //i am lucy, age 18, alex
    
    tp = 'i am {}, age {}, {}'.format('lucy', 18)
    print(tp)       //会报错,有三个{},只有两个值
    
    tp = 'i am {2}, age {1}, {0}'.format('lucy', 18, 'alex') 
    print(tp)     //i am alex, age 18, lucy  按索引取值
    
    tp = 'i am {1}, age {1}'.format('lucy', 18, 'alex')
    print(tp)     // i am 18, age 18   按索引取值
    
    tp = 'i am {name}, age {age}, really {name}'.format(name='lucy', age=18)
    print(tp)      // i am lucy, age 18, really lucy    按key取值
    
    tp = 'i am {name}, age {age}, really {name}'.format(**{'name':'lucy', 'age':18})    
    print(tp)    //i am lucy, age 18, really lucy  **后面是字典格式
    
    tp = 'i am {}, age {}'.format(*['lucy', 18])
    print(tp)       // i am lucy, age 18    *后面是list格式
    
    tp = 'i am {:s}, age {:d}'.format(*['lucy', 18])
    print(tp)      // i am lucy, age 18      s/d分别表示类型
    
    tp = 'i am {:d}, age {:s}'.format(*['lucy', 18])
    print(tp)     //报错  ValueError: Unknown format code 'd' for object of type 'str'
    
    tp = 'numbars:{:b},{:o},{:d},{:x},{:X},{:%}'.format(15,15,15,15,15,15)
    print(tp)    // numbars:1111,17,15,f,F,1500.000000%  
    

    相关文章

      网友评论

          本文标题:05 python 中字符串拼接的几种方法

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