Lesson Overview

Greetings! In today's lesson, we'll explore Python's string methods: split(), join(), strip(), and learn how to perform type conversions. Python's robust built-in string methods simplify text processing, enhancing the readability and efficiency of our code.

Understanding Python's 'split()' Function

Constructing strings frequently entails dividing them into smaller sections or 'tokens'. The split() function in Python achieves this goal by breaking a string into a list of substrings using a specified delimiter. If no delimiter is provided, it splits the string by a single whitespace character.

sentence = 'Python is fun!'
words = sentence.split() # no delimiter provided, splitting by whitespace
print(words)  # Output: ['Python', 'is', 'fun!']

In the example above, we observe that split() divides sentence into words. We can also opt for different delimiters, such as a comma.

data = 'John,Doe,35,Engineer'
info = data.split(',') # provided a ',' delimiter
print(info)  # Output: ['John', 'Doe', '35', 'Engineer']
Exploring the 'join()' Method

Conversely, Python's join() method concatenates, or 'joins', strings into a single string:

words = ['Programming', 'with', 'Python', 'is', 'exciting!']
sentence = ' '.join(words)
print(sentence)  # Output: 'Programming with Python is exciting!'

Here, join() takes a list of words, which are strings, and merges them into a sentence — a single string, using a space as a delimiter.

Mastering the 'strip()' Method

Discerning extra spaces in strings can prove challenging, and they may lead to problems. Python's strip() method removes leading and trailing spaces, tab or newline characters from a string:

name = '    John Doe    \t\n'
name = name.strip()
print(name)  # Output: 'John Doe'

Furthermore, we can use lstrip() and rstrip() to remove spaces, tabs, and newline characters from the left and right of a string, respectively:

name = '    John Doe    '
print(name.lstrip())  # Output: 'John Doe    '
print(name.rstrip())  # Output: '    John Doe'
Python Type Conversions
Sign up
Join the 1M+ learners on CodeSignal
Be a part of our community of 1M+ users who develop and demonstrate their skills on CodeSignal