.split() are two string methods in Python that are used for joining and splitting strings, respectively.
.join()method is used to concatenate elements from an iterable (e.g., a list, tuple, or string) into a single string, using the calling string as the separator.
# Joining a list of words into a single string with space as separator
words = ["Hello", "world", "Python"]
sentence = " ".join(words)
# Output: "Hello world Python"
# Joining a list of numbers into a single string with a comma as separator
numbers = [1, 2, 3, 4, 5]
num_str = ",".join(map(str, numbers))
# Output: "1,2,3,4,5"
.split()method is used to split a string into a list of substrings based on a specified delimiter. If no delimiter is provided, it splits the string on whitespace.
# Splitting a string into a list of words (default delimiter is whitespace)
text = "Hello world Python"
words = text.split()
# Output: ['Hello', 'world', 'Python']
# Splitting a string into a list using a comma as the delimiter
csv_data = "John,Doe,30,New York"
data_list = csv_data.split(",")
# Output: ['John', 'Doe', '30', 'New York']
- We can also specify the maximum number of splits by providing an optional second argument to
.split(). For example,
These methods are commonly used when working with text data, such as parsing CSV files with
.split() or constructing strings from multiple parts with