Advanced String Manipulation
1. Splitting Strings (.split())
The .split() method breaks a string into a list of substrings based on a specified delimiter (separator). If no delimiter is specified, it splits by whitespace.
python data = 'Apple,Banana,Cherry,Date'
Split by comma
fruits = data.split(',') print(fruits) # Output: ['Apple', 'Banana', 'Cherry', 'Date']
sentence = 'Python is fun to learn' words = sentence.split() print(words) # Output: ['Python', 'is', 'fun', 'to', 'learn']
2. Joining Strings (.join())
The .join() method is the inverse of split(). It concatenates a list of strings using the string upon which the method is called as the separator.
python words_list = ['Welcome', 'to', 'the', 'course']
Join using a space
result_space = ' '.join(words_list) print(result_space) # Output: Welcome to the course
Join using an underscore
result_underscore = '_'.join(words_list) print(result_underscore) # Output: Welcome_to_the_course
3. Replacing Substrings (.replace())
Replaces all occurrences of a specified substring with another string.
python message = 'The cat sat on the mat. Cat is sleepy.' new_message = message.replace('Cat', 'Dog') print(new_message) # Output: The Dog sat on the mat. Dog is sleepy.
You can limit the number of replacements
limited_replace = message.replace('the', 'a', 1) print(limited_replace) # Output: The cat sat on a mat. Cat is sleepy.