Split and Join Functions- Really great!!
1. split() function:
The split()
function splits a string into a list of substrings based on a specified separator.
Syntax: list_of_words = string.split(separator)
Examples:
# Split a sentence by spaces text = "This is a string to be split."
word_list = text.split()
print(word_list)
# Output: ['This', 'is', 'a', 'string', 'to', 'be', 'split.']
# Split a CSV string by commas
csv_data = "name,age,citynAlice,30,New YorknBob,25,Los Angeles"
data_list = csv_data.split("n")
# Split by newlines first for row in data_list:
fields = row.split(",") # Split each row by commas within the loop print(fields)
# Output: [['name', 'age', 'city'], ['Alice', '30', 'New York'], ['Bob', '25', 'Los Angeles']] # Split with a custom delimiter
code_snippet = "print('Hello, world!')"
words = code_snippet.split("'")
# Split by single quotes print(words)
# Output: ['print(', 'Hello, world!', ')']
string
: The string you want to split.
separator
(optional): The delimiter used to split the string. If not specified, whitespace (spaces, tabs, newlines) is used by default.
2. join() function:
The join()
function joins the elements of an iterable (like a list) into a single string, inserting a separator between each element.
Syntax:joined_string = separator.join(iterable)
separator
: The string to insert between elements.
iterable
: The iterable (list, tuple, etc.) containing the elements to join.
Examples:
words = ["Hello", "world", "how", "are", "you?"] joined_text = " ".join(words)
# Join with spaces print(joined_text)
# Output: Hello world how are you?
# Join with a custom separator
data = ["apple", "banana", "cherry"]
comma_separated = ",".join(data)
# Join with commas
print(comma_separated)
# Output: apple,banana,cherry
# Join lines for a multi-line
string lines = ["This is line 1.", "This is line 2."]
multiline_text = "n".join(lines)
print(multiline_text)
# Output: This is line 1.
# This is line 2.
Key Points:
- Both
split()
andjoin()
work with strings and iterables. split()
returns a list of substrings, whilejoin()
returns a single string.- You can use custom separators for both functions.
- These functions are versatile for various string manipulation tasks.
Head to Next
Discover more from HintsToday
Subscribe to get the latest posts sent to your email.