-1

I've a small script to find and replace strings since most text editors fail to do so for multiple files. When I pass newline character(\n) as input, the python converts the slash to double slash and it no more stays are newline character. So, my search and replace fails. enter image description here

++++++++++++++++++++++++++++++++++++

Adding suggested solutions here:

Solution 1.

As suggested by @Xu Qiushi

from shlex import quote as q

from ast import literal_eval as le

a = le(q(input()))

allows to take \n as it is.

Solution 2:

Directly providing a dictionary as dict_a = {'।\s' : '।\n'}

etc. works fine for search.

1 Answers1

0

Workaround solution :

a= input()
if (a == "\\n"):
  a="\n"
b = """hello
lad"""
print(a in b)

I wouldn't recommend user entering special character

Solution 2:

`a=input()
 if(a == "new"):
   a="\n"`
Maghil vannan
  • 435
  • 2
  • 6
  • 19
  • Yes, it appears that there is no way apart from replacing \\n with \n. – lalitaalaalitah Jul 02 '20 at 04:48
  • Now, just consider that if I've to do it for \s \t and whatever not, it'll be more troublesome. Trying to use string_a.replace('\\', '\') doesn't work and using string_a.replace('\\', '"\\"') gives undesired result. Any suggestions here. – lalitaalaalitah Jul 02 '20 at 04:50
  • Python converts it since it's a bad idea letting users enter special character may break the program – Maghil vannan Jul 02 '20 at 04:52
  • So, it appears that instead of using \n, I've to enter literal as suggested by @Xu Qiushi. But, I wonder whether the regex search will work then? – lalitaalaalitah Jul 02 '20 at 05:00
  • You could use a =ast.literal_eval(shlex.quote(a)) – Maghil vannan Jul 02 '20 at 05:06
  • 1
    yes, this is enough for now. BTW, if there were no solutions for this, then providing {search_string : replacement_string} library was the only way. – lalitaalaalitah Jul 02 '20 at 05:12