Python ALL Eyes on Strings- String Data Type & For Loop Combined

by lochan2014 | Feb 5, 2025 | Python | 0 comments

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() and join() work with strings and iterables.
  • split() returns a list of substrings, while join() returns a single string.
  • You can use custom separators for both functions.
  • These functions are versatile for various string manipulation tasks.

Head to Next

Written By

undefined

Related Posts

Spark SQL- operators Cheatsheet- Explanation with Usecases

Spark SQL Operators Cheatsheet 1. Arithmetic Operators OperatorSyntaxDescriptionExample+a + bAdds two valuesSELECT 5 + 3;-a – bSubtracts one value from anotherSELECT 5 – 3;*a * bMultiplies two valuesSELECT 5 * 3;/a / bDivides one value by anotherSELECT 6 / 2;%a %…

Read More

Submit a Comment

Your email address will not be published. Required fields are marked *