.join()
and .split()
are two string methods in Python that are used for joining and splitting strings, respectively.
.join()
Method:
- The
.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. - Syntax:
"separator".join(iterable)
- Example:
# Joining a list of words into a single string with space as separator
words = ["Hello", "world", "Python"]
sentence = " ".join(words)
print(sentence)
# 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))
print(num_str)
# Output: "1,2,3,4,5"
.split()
Method:
- The
.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. - Syntax:
string.split(delimiter)
- Example:
# Splitting a string into a list of words (default delimiter is whitespace)
text = "Hello world Python"
words = text.split()
print(words)
# 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(",")
print(data_list)
# 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,string.split(delimiter, maxsplit)
.
These methods are commonly used when working with text data, such as parsing CSV files with .split()
or constructing strings from multiple parts with .join()
.