strip()

strip(): Removes space or chars from left & right side of the string
By default strip() will remove space from left(leading) and right(trailing) of the string, we can also specify chars to be removed
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

Handling Multiple Character Removal

strip() can remove multiple characters, but only from the beginning and end of the string:

my_str = '*$@*Python@$*'
print(my_str.strip('*$@'))  # Output: 'Python'

Use Case: Cleaning User Input

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'

Removing Leading and Trailing Dots

Use strip() to clean up special characters at the ends of a string:

my_str = '...Python...'
print(my_str.strip('.'))  # Output: 'Python'

Use Case: Trimming Whitespace from File Input

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)

Difference between strip(), lstrip(), and rstrip()

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


Subscribe to our YouTube Channel here


Subscribe

* indicates required
Subscribe to plus2net

    plus2net.com







    Python Video Tutorials
    Python SQLite Video Tutorials
    Python MySQL Video Tutorials
    Python Tkinter Video Tutorials
    We use cookies to improve your browsing experience. . Learn more
    HTML MySQL PHP JavaScript ASP Photoshop Articles FORUM . Contact us
    ©2000-2024 plus2net.com All rights reserved worldwide Privacy Policy Disclaimer