my_str=' Plus2net '
output=my_str.strip()
print(output)
my_str='*****plus2net**'
output=my_str.strip('*')
print(output) # removes * from both sides
my_str='*#*# plus2net *#*#'
output=my_str.strip('*# ')
print(output) # removes * ,# and space from both sides
Output is here
plus2net
plus2net
plus2net
strip() can remove multiple characters, but only from the beginning and end of the string:
my_str = '*$@*Python@$*'
print(my_str.strip('*$@')) # Output: 'Python'
When processing form data or reading from files, strip() can help remove unwanted whitespace:
user_input = ' John Doe '
clean_input = user_input.strip()
print(clean_input) # Output: 'John Doe'
Use strip() to clean up special characters at the ends of a string:
my_str = '...Python...'
print(my_str.strip('.')) # Output: 'Python'
When reading lines from a file, strip() is helpful to remove trailing newlines or extra spaces:
with open('data.txt', 'r') as file:
for line in file:
clean_line = line.strip()
print(clean_line)
strip() removes characters from both sides, while lstrip() and rstrip() remove characters from the left and right respectively:
text = " Hello World "
print(text.lstrip()) # Output: "Hello World "
print(text.rstrip()) # Output: " Hello World"
All String methods