1, using the operator " + "
>>> s1 = 'abcdefg' >>> s2 = '12345' >>> s1 + s2 'abcdefg12345'
This "+" is overloaded operator actually calls str .__ add__ built-in method.
>>> str.__add__ (s1,s2) 'abcdefg12345'
When this method when large volumes of data, will take up more resources.
If only a very simple string concatenation can be used, which is more simple.
2, using str.join ()
>>> help(str.join) Help on method_descriptor: join(...) S.join(iterable) -> string Return a string which is the concatenation of the strings in the iterable. The separator between elements is S.
Passing an iterator object is used as a delimiter strings S connected objects.
Example:
>>> ';'.join(['abc','123',456,'xyz']) Traceback (most recent call last): File "<pyshell#46>", line 1, in <module> ';'.join(['abc','123',456,'xyz']) TypeError: sequence item 2: expected string, int found >>> ';'.join(['abc','123','456','xyz']) 'abc;123;456;xyz' >>> ';'.join(['abc','123','456','xyz']) 'abc;123;456;xyz' >>> ''.join(['abc','123','456','xyz']) 'abc123456xyz' >>> ' '.join(['abc','123','456','xyz']) 'abc 123 456 xyz'
Take the above example list is non-string, a string of splicing, there are two methods
Method One: list comprehensions
>>> ''.join([str(x) for x in ['abc','123',456,'xyz']]) 'abc123456xyz'
Each item in the list by str (x) into a string.
By means of a list of analytical formula will generate a temporary list, if the list is long, it will result in larger waste. Not recommended for use.
Method two: generator expression
>>> (str(x) for x in['abc','123',456,'xyz'] ) <generator object <genexpr> at 0x02C60B70>
The above list of parsed block number "[]" to parentheses "()" becomes the object generator. When the generator object for each execution, it generates a, unlike the list of one-time parsing all listed, so more to save resources. Recommended .
>>> ''.join(str(x) for x in ['abc','123',456,'xyz']) 'abc123456xyz'
Generator expressions as parameters can not write parentheses "()"
Reproduced in: https: //www.cnblogs.com/smulngy/p/8871854.html