1. 程式人生 > >Python 字串拼接

Python 字串拼接

+ :

1 s1 = 'a'
2 s2 = 'b'
3 s3 = 'c'
4 s = 'I have ' + s1 +', ' + s2 + ', ' + s3
5 輸出: 'I have a, b, c'

%:

1 s1 = 'a'
2 s2 = 'b'
3 s3 = 'c'
4 s = 'I have %s, %s, %s'%(s1, s2, s3)
5 輸出: 'I have a, b, c'

.format:

1 s1 = 'a'
2 s2 = 'b'
3 s3 = 'c'
4 s = 'I have {}, {}, {}'.format(s1, s2, s3)
5 輸出: 'I have a, b, c'

推薦使用 .format 和 %方式拼接字串。