What exactly does the .join() method do?

0 votes
I'm pretty new to Python and am completely confused by .join() which I have read is the preferred method for concatenating strings.

I tried:

strid = repr(595)
print array.array('c', random.sample(string.ascii_letters, 20 - len(strid)))
    .tostring().join(strid)
and got something like:

5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5
Why does it work like this? Shouldn't the 595 just be automatically appended?
Oct 10, 2018 in Python by ana1504.k
• 7,890 points
28 views

1 answer to this question.

0 votes
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
answered Oct 10, 2018 by SDeb
• 13,210 points

Related Questions In Python

0 votes
1 answer

What exactly does the .join() method do?

Look carefully at your output: 5wlfgALGbXOahekxSs9wlfgALGbXOahekxSs5 ^ ...READ MORE

answered May 30, 2018 in Python by charlie_brown
• 7,720 points
30 views
0 votes
1 answer

What does the map() method do in Python?

The map() function in Python is a ...READ MORE

answered Jun 17 in Python by anonymous
36 views
+1 vote
1 answer

What does the Raise keyword do in Python?

Hi! I think I can answer this - ...READ MORE

answered Jan 25 in Python by Nymeria
• 3,520 points
85 views
0 votes
1 answer
0 votes
1 answer

Python join: why is it string.join(list) instead of list.join(string)?

This is because join is a "string" ...READ MORE

answered Jul 30, 2018 in Python by Priyaj
• 57,300 points
82 views
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 6 in Python by Neha
• 330 points

edited Jul 8 by Kalgi 423 views
0 votes
1 answer

What does the return statement do in Python?

The print() function is use to write ...READ MORE

answered Oct 1, 2018 in Python by SDeb
• 13,210 points
123 views
0 votes
1 answer

What does hash do in python?

A hash is an fixed sized integer ...READ MORE

answered Oct 15, 2018 in Python by SDeb
• 13,210 points
44 views