简体   繁体   English

多行字符串到原始字符串 Python

[英]Multiline String to raw string Python

I have a multiline string.我有一个多行字符串。 I need to convert that string to raw string without using r' ' while declaring the variable.我需要在声明变量时不使用 r' ' 将该字符串转换为原始字符串。 My main motive is to convert \n present in line "print("Entered Name: {}\n".format(str1))" and not to convert other \n in the multiline string.我的主要动机是转换 \n 出现在行"print("Entered Name: {}\n".format(str1))"而不是转换多行字符串中的其他 \n 。

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()'''

Note: I am not able to use string=r' ' ' # Initializing Function named main()...注意:我无法使用 string=r' ' ' # Initializing Function named main()...

Code Thant I tried but didn't work:代码 Thant 我试过但没有用:

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()'''
string=r"{}".format(string)
string = string.replace(r'\n', '')
print(string)

Thanks!谢谢!

As I already said the last time you asked You cannot make a raw string without the r prefix .正如我上次询问时所说,您不能在没有r前缀的情况下制作原始字符串 That is, by definition, what makes it a raw string.也就是说,根据定义,是什么使它成为原始字符串。 You can use a normal, non-raw string, and just escape the escape:您可以使用普通的非原始字符串,然后转义:

string='''# Initializing Function named main()
    ...
    print("Entered Name: {}\\n".format(str1))
    ...
main()'''

Note extra backslash, which makes the string use an actual backslash followed by an n in the string there, while the literal newlines remain newlines, allowing you to replace one without affecting the other.注意额外的反斜杠,这使得字符串使用实际的反斜杠后跟字符串中的n ,而文字换行符仍然是换行符,允许您替换一个而不影响另一个。

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

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