What exactly does the .join() method do?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Over a Mysterious Island
--
Chapters
00:00 Question
00:40 Accepted answer (Score 313)
01:38 Answer 2 (Score 96)
02:20 Answer 3 (Score 61)
02:56 Answer 4 (Score 8)
03:14 Thank you
--
Full question
https://stackoverflow.com/questions/1876...
Accepted answer links:
[join()]: https://docs.python.org/3/library/stdtyp...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #list #string
#avk47
ACCEPTED ANSWER
Score 318
Look carefully at your output:
5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
^ ^ ^
I've highlighted the "5", "9", "5" of your original string. The Python join() method is a string method, and takes a list of things to join with the string. A simpler example might help explain:
>>> ",".join(["a", "b", "c"])
'a,b,c'
The "," is inserted between each element of the given list. In your case, your "list" is the string representation "595", which is treated as the list ["5", "9", "5"].
It appears that you're looking for + instead:
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid
ANSWER 2
Score 97
join takes an iterable thing as an argument. Usually it's a list. The problem in your case is that a string is itself iterable, giving out each character in turn. Your code breaks down to this:
"wlfgALGbXOahekxSs".join("595")
which acts the same as this:
"wlfgALGbXOahekxSs".join(["5", "9", "5"])
and so produces your string:
"5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5"
Strings as iterables is one of the most confusing beginning issues with Python.
ANSWER 3
Score 61
To append a string, just concatenate it with the + sign.
E.g.
>>> a = "Hello, "
>>> b = "world"
>>> str = a + b
>>> print str
Hello, world
join connects strings together with a separator. The separator is what you
place right before the join. E.g.
>>> "-".join([a,b])
'Hello, -world'
Join takes a list of strings as a parameter.
ANSWER 4
Score 8
join() is for concatenating all list elements. For concatenating just two strings "+" would make more sense:
strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
.tostring() + strid