簡體   English   中英

如何在Python中不包含'\\ n'來打印字符串

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

假設我的字符串是:

' Hai Hello\nGood eve\n'

如何消除兩者之間的'\\n'並使字符串打印如下:

 Hai Hello Good eve 

如果您不想在print語句末尾添加換行符:

import sys
sys.stdout.write("text")

您可以使用replace方法:

>>> a = "1\n2"
>>> print a
1
2
>>> a = a.replace("\n", " ")
>>> print a
1 2

在Python 2.6中:

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

在Python 3.0中

print("Hello", end = " ")
print("This is on the same line")

在“打印”后添加逗號:

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

在Python 3.0中,“打印”已經消失了

我意識到這是一個非常古老的帖子,但我也遇到了這個問題,並希望為了清晰起見而添加它。 我相信,原始用戶要求的是如何讓操作系統將字符串“some text \\ nsome more text”解釋為:

一些文字

更多文字

而不僅僅是打印:

“一些文字\\ nsome更多文字”

答案是它已經在解釋了。 在ubuntu中,我遇到了它在將新行字符放入字符串時轉義它而沒有我要求它的問題。 所以字符串:

“一些文字\\ nsome更多文字”

實際上是

“一些文字\\\\ nsome更多文字”

所需要的只是使用mystring.replace("\\\\\\n", "\\n")並實現所需的輸出。 希望這是明確的,並幫助一些未來的人。

很老的帖子,但似乎沒有人成功回答你的問題。 兩個可能的答案:

首先,你的字符串實際上是Hai Hello\\\\\\\\nGood eve\\\\\\\\n打印為Hai Hello\\\\nGood eve\\\\n由於轉義了\\\\\\\\ 簡單的修復就是mystring.replace("\\\\\\\\n","\\\\n") (參見http://docs.python.org/reference/lexical_analysis.html#string-literals

或者,您的字符串不是字符串,可能是元組。 當我以為我有一個字符串並且從未注意到它是如何打印時我只是遇到了類似的錯誤,因為它是一個長字符串。 我的印刷是:

(“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 metin condimentum tincidunt sed vitae magna。\\ nInteger nulla odio,sagittis id porta commodo,hendrerit vestibulum risus。\\ n ...,“”)

很容易錯過開頭和結尾的括號,只需注意\\ n's。 打印mystring[0]應解決此問題(或列表/元組中的任何索引等)。

>>> 'Hai Hello\nGood eve\n'.replace('\n', ' ')
'Hai Hello Good eve '

不確定這是否是您要求的,但您可以使用三引號字符串:

print """Hey man
And here's a new line

you can put multiple lines inside this kind of string
without using \\n"""

將打印:

Hey man
And here's a new line

you can put multiple lines inside this kind of string
without using \n

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM