Removing "\n" Between The Line In Multiline String In Python
I want to remove '\n' from the intext in python. I tried many ways but all didn't work. The text suppose to be something like this: string='''# Initializing Function named main() d
Solution 1:
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.
The simplest solution is to use an r-string for the outer one; note the r'''
on the first line:
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.
Solution 2:
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):
# 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', '')
Solution 3:
i = string.find('{}\\n') #is the position of the '{}\n'string = string[:i+2] + string[i+5 :] #should do the trick
Post a Comment for "Removing "\n" Between The Line In Multiline String In Python"