Python String Manipulation: strip, split, and join with Examples
This tutorial demonstrates how to use Python's strip, lstrip, rstrip, split, and join functions to remove characters, divide strings, and concatenate elements, providing code snippets and the corresponding output for each operation.
Day 57 of the learning notes introduces common string extraction, splitting, and merging operations in Python.
strip() removes characters from both ends of a string; by default it removes spaces. Example:
str1 = "today is a nice day"
str2 = "***today is a nice day***"
print(str1.strip()) # today is a nice day
print(str2.strip("*")) # today is a nice day
print(str2.lstrip("*")) # today is a nice day***
print(str2.rstrip("*")) # ***today is a nice daysplit() divides a string into a list based on a separator; default separator is any whitespace.
str3 = "this is a string example...."
print(str3.split())
# ['this', 'is', 'a', 'string', 'example....']
print(str3.split("i"))
# ['th', 's a str', 'ng example....']join() concatenates an iterable of strings using a specified separator.
sep = "-"
tup = ("hello", "every", "body")
print(tup) # ('hello', 'every', 'body')
print(sep.join(tup)) # hello-every-bodyThe printed results correspond to the operations described above.
Lisa Notes
Lisa's notes: musings on daily life, work, study, personal growth, and casual reflections.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
