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

2018-07-02  本文已影响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%  
上一篇下一篇

猜你喜欢

热点阅读