How to print string without double quotes in python

View Discussion

Improve Article

Save Article

  • Read
  • Discuss
  • View Discussion

    Improve Article

    Save Article

    We often come across small issues that turns out to be big. While coding, the small  tasks become sometimes tedious when not handled well. One among those tasks is output formatting in which we require to omit the quotes while printing any list elements. Let’s discuss certain ways in which this can be performed. Method #1 : Using join[] We can simplify this task by using the join method in which we join the strings in the list together by the separator being passed [ in this case comma ] and hence solve the issue. 

    Python3

    test_list = ['Geeks', 'For', 'Geeks']

    print ["The original list is : " + str[test_list]]

    print ["The formatted output is : "]

    print [', '.join[test_list]]

    Output : 

    The original list is : ['Geeks', 'For', 'Geeks']
    The formatted output is : 
    Geeks, For, Geeks

      Method #2 : Using print[] + sep The print function can be used by passing the required container containing the strings and * operator performs the task of joining each string in this case. The separator being used is defined using the sep keyword passed as second argument in print. 

    Python3

    test_list = ['Geeks', 'For', 'Geeks']

    print ["The original list is : " + str[test_list]]

    print ["The formatted output is : "]

    print[*test_list, sep =', ']

    Output : 

    The original list is : ['Geeks', 'For', 'Geeks']
    The formatted output is : 
    Geeks, For, Geeks


    In the Python interactive prompt, if you return a string, it will be displayed with quotes around it, mainly so that you know it's a string.

    If you just print the string, it will not be shown with quotes [unless the string has quotes in it].

    >>> 1 # just a number, so no quotes
    1
    >>> "hi" # just a string, displayed with quotes
    'hi'
    >>> print["hi"] # being *printed* to the screen, so do not show quotes
    hi
    >>> "'hello'" # string with embedded single quotes
    "'hello'"
    >>> print["'hello'"] # *printing* a string with embedded single quotes
    'hello'
    

    If you actually do need to remove leading/trailing quotation marks, use the .strip method of the string to remove single and/or double quotes:

    >>> print["""'"hello"'"""]
    '"hello"'
    >>> print["""'"hello"'""".strip['"\'']]
    hello
    

    • Problem Formulation
    • Solution 1: print[]
    • Solution 2: string.strip[]
    • Solution 3: string.replace[]
    • Solution 4: re.sub[]
    • Where to Go From Here?

    Problem Formulation

    In Python’s interactive mode, each line is assumed to be an expression that is evaluated. The return value is provided to the user. Thus, if you evaluate a string expression or call a function or an operation that returns a string, the output will display quotes around the string to tell the user that this is a string result:

    # Quotes
    >>> 'hello world'
    'hello world'

    For example, if you’d simply evaluate a mathematical operation with an integer result, no quotes would be displayed:

    >>> 40 + 2
    42

    How can you get rid of the quotes and print a Python string without the quotes?

    Solution 1: print[]

    When in interactive mode, a string result is displayed with single quotes around it to indicated that the result is a string. But if you pass the resulting string in a print[...] function call as an argument, the quotes disappear.

    # No Quotes
    >>> print['hello world']
    hello world

    This is because the print[] function automatically converts each argument to its string representation and prints it to the standard output. Because all print outputs are strings, it doesn’t provide value to indicate the string type with enclosing types. So, Python just skips them.

    Feel free to watch the following video to dive deeper into the function:

    Python Print Function [And Its SECRET Separator & End Arguments]

    Solution 2: string.strip[]

    If you want to remove the enclosing quotes from a string before printing it, you can call the string.strip[] method and pass the single and double quotes characters to be stripped from the beginning and end of the string object on which it is called. For example, the expression '"hello world"'.strip['"\''] removes all enclosing single and double quotes and results in the simple string 'hello world'.

    hi = '"hello world"'
    
    print[hi]
    # "hello world"
    
    print[hi.strip['"\'']]
    # hello world

    Note that the strip[] method removes all characters in the provided string argument. As you need to enclose the string argument in double or single quotes itself, you need to escape the character you used to enclose the string argument. This removes the special meaning [=close the string] from the quote and tells Python to use the quote character.

    Again, feel free to watch the following video to dive deeper into the function:

    Python String Methods [Ultimate Guide]

    Solution 3: string.replace[]

    The brute-force approach to remove all quotes from a given string, not just the enclosing ones, is to use the string.replace[] method and replace every occurrence of a quote with the empty string ''. For example, to first remove all double quotes and then all single quotes from string s, you can chain the function twice via s.replace['"', ''].replace["'", ''].

    >>> s = 'hello """ world \'\'\' !!!'
    >>> s
    'hello """ world \'\'\' !!!'
    >>> s.replace['"', ''].replace["'", '']
    'hello  world  !!!'

    Watch the following video to dive deeper into the function:

    Python String Methods [Ultimate Guide]

    Solution 4: re.sub[]

    The regex function re.sub[P, R, S] replaces all occurrences of the pattern P with the replacement R in string S. It returns a new string. For example, if you call re.sub['["\']', '', s], the result will be the new string with all single or double quotes removed from the string s.

    >>> import re
    >>> s = 'hello """ world \'\'\' !!!'
    >>> re.sub['["\']', '', s]
    'hello  world  !!!'

    The regex pattern '["\']' opens a character class that you can see as an OR relation—it will either match the double quote character " or the single quote character ' [escaped to prevent a syntax error as the last single quote would open a new string that is never closed].

    Yes, there’s another video for learning and improving your understanding of this vital function:

    Python Regex Sub - How to Replace a Pattern in a String?

    Where to Go From Here?

    Enough theory. Let’s get some practice!

    Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.

    To become more successful in coding, solve more real problems for real people. That’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

    You build high-value coding skills by working on practical coding projects!

    Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?

    🚀 If your answer is YES!, consider becoming a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

    If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.

    Join the free webinar now!

    While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.

    To help students reach higher levels of Python success, he founded the programming education website Finxter.com. He’s author of the popular programming book Python One-Liners [NoStarch 2020], coauthor of the Coffee Break Python series of self-published books, computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.

    His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.

    How do you remove double quotes from a string in Python?

    Use str. strip[chars] on str with the quote character '"' as chars to remove quotes from the ends of the string.

    How do you return a string without double quotes in Python?

    2 Answers. Show activity on this post. In the Python interactive prompt, if you return a string, it will be displayed with quotes around it, mainly so that you know it's a string. If you just print the string, it will not be shown with quotes [unless the string has quotes in it].

    How do I remove all quotes from a string in Python?

    To erase Quotes [“”] from a Python string, simply use the replace[] command or you can eliminate it if the quotes seem at string ends.

    How do you remove double quotes from a string?

    To remove double quotes just from the beginning and end of the String, we can use a more specific regular expression: String result = input. replaceAll["^\"|\"$", ""]; After executing this example, occurrences of double quotes at the beginning or at end of the String will be replaced by empty strings.

    Chủ Đề