Home > Software design >  Removing extra spaces from string when it contains a \ character
Removing extra spaces from string when it contains a \ character

Time:12-13

I am getting a string in this form:

my_string = "select \\\"ASSETS\\\" AS \\\"LEASE_ASSETS\\\", count(*) CNT FROM \\\"SIY\\\".\\\"I7_MAIN_ACCOUNT\\\" group by \\\"ASSETS\\\" order by \\\"ASSETS\\\""

I want to remove these \\\, but I am not sure if str.replace() is a good option.

The main thing I want is to get this Table name part from it, like this:

"SIY.I7_MAIN_ACCOUNT"

... which, due to those spaces, I am not able to get. I want to do it by using str.replace(), but it seems both are not working.

CodePudding user response:

If query will be the same then you filter un wanted things one by one then extract your required words

my_string = "select \\\"ASSETS\\\" AS \\\"LEASE_ASSETS\\\", count(*) CNT FROM \\\"SIY\\\".\\\"I7_MAIN_ACCOUNT\\\" group by \\\"ASSETS\\\" order by \\\"ASSETS\\\""
my_string= my_string.replace("\\", '').replace('"', '')
print (my_string[my_string.find('FROM ') len('FROM '):my_string.rfind('group')])

Gives #

SIY.I7_MAIN_ACCOUNT 

CodePudding user response:

There are probably better methods, but I'd turn it into a list and append through that removing any slashes. You can rejoin this string using the .join function afterward.

my_list = list(my_string)
for i in range(len(my_list)):
     if my_list[i] == "/":
          my_list[i] = ""
my_string = ''.join(my_list)

CodePudding user response:

First, watch out, there's some difference between how string escape characters are represented and how they're displayed

>>> my_string = "select \\\"ASSETS\\\" AS \\\"LEASE_ASSETS\\\", count(*) CNT FROM \\\"SIY\\\".\\\"I7_MAIN_ACCOUNT\\\" group by \\\"ASSETS\\\" order by \\\"ASSETS\\\""
>>> my_string
'select \\"ASSETS\\" AS \\"LEASE_ASSETS\\", count(*) CNT FROM \\"SIY\\".\\"I7_MAIN_ACCOUNT\\" group by \\"ASSETS\\" order by \\"ASSETS\\"'
>>> print(my_string)
select \"ASSETS\" AS \"LEASE_ASSETS\", count(*) CNT FROM \"SIY\".\"I7_MAIN_ACCOUNT\" group by \"ASSETS\" order by \"ASSETS\"

However, you can directly use the .replace() method on the string to get rid of these

>>> my_string.replace("\\", "")
'select "ASSETS" AS "LEASE_ASSETS", count(*) CNT FROM "SIY"."I7_MAIN_ACCOUNT" group by "ASSETS" order by "ASSETS"'
  • Related