How to print a string without including '\n' in Python

前端 未结 8 993
没有蜡笔的小新
没有蜡笔的小新 2021-01-01 16:26

Suppose my string is:

\' Hai Hello\\nGood eve\\n\'

How do I eliminate the \'\\n\' in between and make a string print like :

相关标签:
8条回答
  • 2021-01-01 16:35

    Not sure if this is what you're asking for, but you can use the triple-quoted string:

    print """Hey man
    And here's a new line
    
    you can put multiple lines inside this kind of string
    without using \\n"""
    

    Will print:

    Hey man
    And here's a new line
    
    you can put multiple lines inside this kind of string
    without using \n
    
    0 讨论(0)
  • 2021-01-01 16:41

    If you don't want the newline at the end of the print statement:

    import sys
    sys.stdout.write("text")
    
    0 讨论(0)
  • 2021-01-01 16:41

    In Python 2.6:

    print "Hello.",
    print "This is on the same line"
    

    In Python 3.0

    print("Hello", end = " ")
    print("This is on the same line")
    
    0 讨论(0)
  • 2021-01-01 16:46

    Way old post but nobody seemed to successfully answer your question. Two possible answers:

    First, either your string is actually Hai Hello\\\\nGood eve\\\\n printing as Hai Hello\\nGood eve\\n due to the escaped \\\\. Simple fix would be mystring.replace("\\\\n","\\n") (See http://docs.python.org/reference/lexical_analysis.html#string-literals)

    Or, your string isn't a string and possibly a tuple. I just had a similar error when I thought I had a string and never noticed how it was printing as it was a long string. Mine was printing as:

    ("Lorem ipsum dolor sit amet, consectetur adipiscing elit.\nEtiam orci felis, pulvinar id vehicula nec, iaculis eget quam.\nNam sapien eros, hendrerit et ullamcorper nec, mattis at ipsum.\nNulla nisi ante, aliquet nec fermentum non, faucibus vel odio.\nPraesent ac odio vel metus condimentum tincidunt sed vitae magna.\nInteger nulla odio, sagittis id porta commodo, hendrerit vestibulum risus.\n...,"")

    Easy to miss the brackets at the start and end and just notice the \n's. Printing mystring[0] should solve this (or whatever index it is in the list/tuple etc).

    0 讨论(0)
  • 2021-01-01 16:50

    You can use the replace method:

    >>> a = "1\n2"
    >>> print a
    1
    2
    >>> a = a.replace("\n", " ")
    >>> print a
    1 2
    
    0 讨论(0)
  • 2021-01-01 16:50

    Add a comma after "print":

    print "Hai Hello",
    print "Good eve",
    

    Altho "print" is gone in Python 3.0

    0 讨论(0)
提交回复
热议问题