• This topic is empty.
Viewing 1 post (of 1 total)
  • Author
    Posts
  • #3259

    Removing specific characters with strip
    byu/DigitalSplendid inlearnpython

    \

     

    Python’s strip() and split() methods with examples

    Source: Created with the help of ChatGPT

    The strip() and split() methods in Python are string manipulation functions often used to clean and process textual data.

    1. strip()

    The strip() method removes any leading (spaces at the beginning) and trailing (spaces at the end) characters (by default, whitespace characters) from a string. It does not remove spaces inside the string.

    Syntax:

    string.strip([chars])
    
    • chars (optional): Specifies the set of characters to be removed. If omitted, the method will remove whitespace by default.

    Example:

    # Example 1: Using strip with default whitespace removal
    text = " Hello, World! "
    stripped_text = text.strip()
    print(stripped_text) # Output: "Hello, World!"
    
    # Example 2: Removing specific characters
    text = "///Python///"
    stripped_text = text.strip("/")
    print(stripped_text) # Output: "Python"
    

    2. split()

    The split() method breaks a string into a list of substrings based on a specified separator. If no separator is specified, it defaults to splitting at any whitespace (spaces, tabs, or newlines).

    Syntax:

    string.split([separator, maxsplit])
    
    • separator (optional): The delimiter string where the split occurs. If omitted, any whitespace is considered a separator.
    • maxsplit (optional): The maximum number of splits to do. The default is -1, which means “all occurrences.”

    Example:

    # Example 1: Splitting a string with default separator (whitespace)
    text = "Hello, World!"
    split_text = text.split()
    print(split_text) # Output: ['Hello,', 'World!']
    
    # Example 2: Splitting a string with a specified separator
    text = "apple,banana,orange"
    split_text = text.split(',')
    print(split_text) # Output: ['apple', 'banana', 'orange']
    
    # Example 3: Limiting the number of splits
    text = "apple,banana,orange,grape"
    split_text = text.split(',', 2)
    print(split_text) # Output: ['apple', 'banana', 'orange,grape']
    

    Combined Example:

    You can combine both strip() and split() to clean and process data more effectively:

    text = " apple, banana, orange "
    cleaned_text = text.strip().split(", ")
    print(cleaned_text) # Output: ['apple', 'banana', 'orange']
    

    Here, strip() removes leading and trailing spaces, and split() divides the string into a list of fruits based on the separator ", ".

Viewing 1 post (of 1 total)
  • You must be logged in to reply to this topic.
Scroll to Top