How to remove quotes from a String in Python


To remove quotes from within a String in Python, we can make use of the functions such as strip(), re and replace().


Example 1: Remove Leading and Trailing Single Quotes using strip()

    str_with_single_quotes = "'Hello there! How are you?'"
    
    str_without_single_quotes = str_with_single_quotes.strip("'")
    
    print(str_without_single_quotes)
    Output:
    Hello there! How are you?

Note: strip() function can be used only to remove the leading and trailing quotes.


Example 2: Remove Leading and Trailing Double Quotes using regex - re module

    import re
    
    str_with_single_quotes = "He said \"I am not coming!\""
    
    str_without_single_quotes = re.sub(r"\"", "", str_with_single_quotes)
    
    print(str_without_single_quotes)
    Output:
    He said I am not coming!

Example 3: Using replace() function to repalce both single and double quotes

    import re
    
    str_with_single_quotes = "\"This isn't mine\""
    
    str_without_single_quotes = str_with_single_quotes.replace("'", "").replace("\"", "")
    
    print(str_without_single_quotes)
    Output:
    This isnt mine!

Python Repalce Single or Double Quotes Example

Facing issues? Have Questions? Post them here! I am happy to answer!

Author Info:

Rakesh (He/Him) has over 14+ years of experience in Web and Application development. He is the author of insightful How-To articles for Code2care.

Follow him on: X

You can also reach out to him via e-mail: rakesh@code2care.org

Copyright © Code2care 2024 | Privacy Policy | About Us | Contact Us | Sitemap