In [1]: s1 = 'abcdef' In [2]: s2 = '123456' In [3]: s1 + s2 Out[3]: 'abcdef123456' In [4]: str.__ str.__abstractmethods__ str.__getattribute__ str.__name__ str.__add__ str.__getitem__ str.__ne__ str.__base__ str.__getnewargs__ str.__new__ str.__bases__ str.__getslice__ str.__reduce__ str.__basicsize__ str.__gt__ str.__reduce_ex__ str.__call__ str.__hash__ str.__repr__ str.__class__ str.__init__ str.__rmod__ str.__contains__ str.__instancecheck__ str.__rmul__ str.__delattr__ str.__itemsize__ str.__setattr__ str.__dict__ str.__le__ str.__sizeof__ str.__dictoffset__ str.__len__ str.__str__ str.__doc__ str.__lt__ str.__subclasscheck__ str.__eq__ str.__mod__ str.__subclasses__ str.__flags__ str.__module__ str.__subclasshook__ str.__format__ str.__mro__ str.__weakrefoffset__ str.__ge__ str.__mul__ In [4]: str.__add__(s1,s2) Out[4]: 'abcdef123456' In [5]: s1 > s2 Out[5]: True In [7]: str.__gt__(s1,s2) Out[7]: True pl = ["<0112>","<32>","<1024x768>","<1>","<100.0>","<500.0>"] In [7]: s = '' In [8]: for p in pl: ...: s += p ...: In [9]: s Out[9]: '<0112><32><1024x768><1><100.0><500.0>' 使用join函数进行字符串的拼接 In [10]: ';'.join(['abc','xyz','123']) Out[10]: 'abc;xyz;123' In [12]: ''.join(pl) Out[12]: '<0112><32><1024x768><1><100.0><500.0>' In [13]: l = ['abc','xyz',45,'123'] In [14]: l Out[14]: ['abc', 'xyz', 45, '123'] In [16]: ''.join([str(x) for x in l]) Out[16]: 'abcxyz45123' 当我们使用加号(+)操作符去连接大量的字符串时是非常低效率的,因为加号连接会引起内存复制以及垃圾回收操作。 特别的,你永远都不要像下面这样写字符串连接代码: In [21]: for x in pl: ....: s += p ....: print s ....: <500.0><500.0><500.0><500.0><500.0><500.0><500.0> <500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0> <500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0> <500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0> <500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0> <500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0><500.0> In [1]: l = ['abc', 'xyz', 45, '123'] In [2]: l Out[2]: ['abc', 'xyz', 45, '123'] 使用列表解析的方法拼接字符串 In [3]: ''.join([str(x) for x in l]) Out[3]: 'abcxyz45123' 使用生成器表达式的方法拼接字符串 In [5]: (str(x) for x in l) Out[5]: <generator object <genexpr> at 0xb60e3284> In [4]: ''.join(str(x) for x in l) Out[4]: 'abcxyz45123' In [3]: pl Out[3]: ['<0112>', '<32>', '<1024x768>', '<1>', '<100.0>', '<500.0>'] In [4]: s = '' In [5]: for x in pl: ...: s += x ...: print(s) ...: <0112><32><1024x768><1><100.0><500.0> In [6]: ''.join(pl) Out[6]: '<0112><32><1024x768><1><100.0><500.0>' In [7]: l = ['abc','cde',123,456,'efg'] In [8]: l Out[8]: ['abc', 'cde', 123, 456, 'efg'] In [9]: ''.join([str(x) for x in l]) Out[9]: 'abccde123456efg' In [10]: ([str(x) for x in l]) Out[10]: ['abc', 'cde', '123', '456', 'efg'] In [11]: ''.join(str(x) for x in l) Out[11]: 'abccde123456efg' In [12]: (str(x) for x in l) Out[12]: <generator object <genexpr> at 0xb6ac77ac>