Quick question on .join()

Hello all,

I’m just learning and I’ve learned about the Join() method and been using it for a chapter or two. Every time my book lists ‘’.join() where the ‘’ are two apostrophe’s and not a quotation mark. I can’t find anything online showing or mentioning why the ‘’. is there except the occasional ‘#’.join() that I’ll see in some examples online. I assumed perhaps that it was a place to name the new variable that the method is able to create, but clearly my examples are showing me variable_name=’’.join() so that can’t be it.

What are those apostrophes and the period for?

>>> ''.join(['a', 'b', 'c', 'd'])
'abcd'
>>> ', '.join(['a', 'b', 'c', 'd'])
'a, b, c, d'

The '' makes an empty string. .join() calls a method on the string. A method is somewhat like a function, but attached to a specific object. The join() method of string objects concatenates strings with the string whose method is being called as the separator.

That should give you most search terms to learn more.

OMG, thank you! That’s so useful, and I’m sure we’re getting there, but I could have handled knowing that before using it for 3 bits of code now :grinning:

They’re not apostrophes, they are single quotation marks.

You can use double quotation marks if you prefer: Python doesn’t care which you use.

# These are exactly the same.
result = ''.join(['Hello', ' ', 'World!'])
result = "".join(['Hello', ' ', 'World!'])

The dot refers to a method or attribute of the value before the dot:

mylist.append  # append method of the list called "mylist"

''.join  # join method of the empty string ''

So to join a list of substrings with nothing between them, use ‘’ or “”.
To join with something else, use that string:

substrings = ["aa", "bb", "cc"]
print( "".join(substrings) )
print( " ".join(substrings) )
print( "~~".join(substrings) )

Python doesn’t care if you use ‘’ or “” for your strings, you can use
whichever you prefer.