简体   繁体   English

删除 python 中多行字符串中的行之间的“\n”

[英]Removing “\n” between the line in multiline string in python

I want to remove "\n" from the intext in python.我想从 python 的 intext 中删除“\n”。 I tried many ways but all didn't work.我尝试了很多方法,但都没有奏效。 The text suppose to be something like this:文本假设是这样的:

string='''# Initializing Function named main()
def main () :
    str1 = None
    str2 = None
    age=16
    str1=str(input())
    str2=str(input())
    print("Entered Name: {}\n".format(str1))
    print("Entered Website:{}".format(str2))
# Calling the main Function
main()'''

In line "print("Entered Name: {}\n".format(str1))" there is \n which I need to remove without removing other \n from muliline string."print("Entered Name: {}\n".format(str1))" 行中,我需要删除 \n 而无需从 muliline 字符串中删除其他 \n 。 Thanks!谢谢!

The problem is that the \n is interpreted by the ''' string, but you want it to be left in place and processed by the inner " string.问题是\n'''字符串解释,但您希望它留在原地并由内部"字符串处理。

The simplest solution is to use an r-string for the outer one;最简单的解决方案是使用 r 字符串作为外部字符串; note the r''' on the first line:注意第一行的r'''

string=r'''# Initializing Function named main()
def main () :
    str1 = None
    str2 = None
    age=16
    str1=str(input())
    str2=str(input())
    print("Entered Name: {}\n".format(str1))
    print("Entered Website:{}".format(str2))
# Calling the main Function
main()'''

With that change, the inner \n should work correctly and you'll probably no longer need to remove it.通过该更改,内部\n应该可以正常工作,并且您可能不再需要将其删除。

Declare the multiline string as a raw string so the \n isn't escaped, then replace it (using another raw string so it is not escaped yet again):将多行字符串声明为原始字符串,这样\n就不会被转义,然后替换它(使用另一个原始字符串,这样它就不会再次被转义):

# r before the ''' makes it a raw string
string=r'''# Initializing Function named main()
def main () :
    str1 = None
    str2 = None
    age=16
    str1=str(input())
    str2=str(input())
    print("Entered Name: {}\n".format(str1))
    print("Entered Website:{}".format(str2))
# Calling the main Function
main()'''
string = string.replace(r'\n', '')
i = string.find('{}\\n') #is the position of the '{}\n'
string = string[:i+2] + string[i+5 :] #should do the trick

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM