Lesson 2: Python .join()
- ESTIMATED TIME: 7 mins.
- DIFFICULTY: Intermediate
- FUNCTIONS: .join()
- 5 EXERCISES
.join()
is a useful string method that will join strings with a specified string or character.
- Inside
.join()
‘s parenthesis goes the strings to be added together. - In front of
.join()
goes the glue, the character that will add the strings together.
Let’s see examples:
Used Where?
- Accessing substrings in strings. (email address or domain extraction can be an example, but examples are infinite)
- Extracting parts of lists
- Extracting parts of tuples.
Syntax do(s)
1) Follow the syntax notation [start:end:step]
2) If start is not given it will start from 0 (zero)
Syntax don't(s)
1) Dictionaries have no orders and their values are accessed by keys. So you can't slice a dictionary.
Function 1: .join()
No new function will be introduced in this lesson.
Example 1
>>> lst = [“Pacific”, “Atlantic”, “Indian”]
>>> a = ” “.join(lst)
>>> print(a)
‘Pacific Atlantic Indian’
We used a space character in quotes in front of .join()
and then a list of strings that will be joined together inside the parenthesis.
Example 2
>>> lst = [“Pacific”, “Atlantic”, “Indian”]
>>> a = “+”.join(lst)
>>> print(a)
‘Pacific+Atlantic+Indian’
+
sign Example 3
Let’s do everything in one line just for fun.
>>> print(“x”.join(“Hello”))
Hxexlxlxo
Example 4
Maybe an email task with your big data:
>>> email_ = [“michael”, “ucla.edu”]
>>> email_full = “@”.join(email_)
>>> print(email_full)
michael@ucla.edu
Tips
1- .join() function is usually confused regarding what goes in front of it and what goes inside the parenthesis.
If you pay attention to this you won’t have much problem utilizing this super useful string method in future.
So, glue (character that will join strings together) should be in front of .join() function. And the strings to be added together should be inside the parenthesis.
Example 5
Below example will give everything until last 2 elements
>>> a = list(range(10))
>>> print(a[:-2])
[0, 1, 2, 3, 4, 5, 6, 7]
Example
Getting the last element:
>>> a = list(range(10))
>>> print(a[-1])
[9]
Advanced Concepts (Optional)
Next Lesson: .split() method