Home > Software engineering >  How do I split a string with backward slashes in from the backward slashes substring using split() o
How do I split a string with backward slashes in from the backward slashes substring using split() o

Time:12-26

I have a string which looks similar to 123456 \\RE1NUM=987 and I have been trying to split it \\RE1NUM=.

I have tried .split("\\RE1NUM=") and it gives ['123456 \\', '987']. I believe backward slashes are being interpreted as escape characters. The final list I need will be ['123456 ', '987'].

The "string" is actually a line I am reading from a file object. It does work when isolated and tested on string, but fails when used on file's line. (I'll try to recreate this problem on a test file and paste the contents here.)

CodePudding user response:

Can you try to use a different editor? cause I have tried to use the python shell in my terminal and it did indeed give me the desired output as follows enter image description here

CodePudding user response:

replit link: https://replit.com/@shivvohra/StackOverflow1?v=1

Code:

string = '123456 \RE1NUM=987' var = string.replace("\", " ").split()

first_six_letters = var[0] last_few_numbers = var1.split('=')

last_three_letters = last_few_numbers.pop(1)

combined = [first_six_letters, last_three_letters]

print(combined)

Output: ['123456', '987']

enter image description here

CodePudding user response:

for example code:

string =  "123456     \\RE1NUM=987"
result =  string.split("\\\\RE1NUM=")     
print(result)
  • Related