Home > Backend Development > Python Tutorial > Why does `.join()` insert separators when concatenating strings?

Why does `.join()` insert separators when concatenating strings?

Patricia Arquette
Release: 2024-11-09 14:05:03
Original
273 people have browsed it

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"
Copy after login

In the given example:

strid = repr(595)
array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring().join(strid)
Copy after login

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
Copy after login

Solution: To concatenate strings without inserting a separator, use instead:

print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid
Copy after login

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!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template