Home > Article > Backend Development > Why does `.join()` insert separators when concatenating strings?
Understanding the Python .join() Method
Python's .join() method is a powerful tool for string concatenation, often preferred over alternatives like and str.format.
Question: Why does .join() behave unexpectedly when concatenating strings?
Answer: The .join() method takes a list of strings and inserts the provided separator string between each element. For example:
",".join(["a", "b", "c"]) == "a,b,c"
In the given example:
strid = repr(595) array.array('c', random.sample(string.ascii_letters, 20 - len(strid))) .tostring().join(strid)
The string "595" is converted into a list of characters: ["5", "9", "5"]. Then, the separator string is inserted between each character, resulting in the output:
5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
Solution: To concatenate strings without inserting a separator, use instead:
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid))) .tostring() + strid
The above is the detailed content of Why does `.join()` insert separators when concatenating strings?. For more information, please follow other related articles on the PHP Chinese website!