简体   繁体   中英

Remove until specific char in string (Python)

I want to remove something from the start and end of a string before writing to the .txt

I'm reading an incoming string from a serial port. I want to write the string to a .txt file, which I can do. I've tried using the rstrip() (also tried strip() ) function to remove the 'OK' in the end, but with no luck.

Ideally, I want the program to be dynamic so I can use it for other files. This gives a problem, because the unwanted text in the start and end of the string might vary, so I can't look for specific chars/words to remove.

While this is said, all unwanted text in the start of the string will start with a '+' like in the example below (It might be possible to check if the first line starts with a '+' and remove it if it does. This would be ideal).

def write2file():
    print "Listing local files ready for copying:"
    listFiles()
    print 'Enter name of file to copy:'
    name = raw_input()
    pastedFile = [] 
    tempStr = readAll('AT+URDFILE="' + name + '"') #Calls another function who reads the file locally and return it in a string
    tempStr = tempStr.rstrip('OK') #This is where I try to remove the 'OK' I know is going to be in the end of the string
    pastedFile[:0] = tempStr #Putting the string into a list. Workaround for writing 128 bytes at a time. I know it's not pretty, but it works :-)
    print 'Enter path to file directory'
    path =  raw_input()
    myFile = open(join(path, name),"w")
    while len(pastedFile):
        tempcheck  = pastedFile[0:128]
        for val in tempcheck:
            myFile.write(val)
        del pastedFile[0:128]
    myFile.close()

I expect the .txt to include all the text from the local file, but remove the OK in the end. When program is run it returns:

+URDFILE: "develop111.txt",606,"** ((content of local file)) OK

The 'OK' I wanted to be removed is still in there.

The text "+URDFILE: "develop111.txt",606," is also unwanted in the final .txt file.

So summarizes the problem:

How can I remove the unwanted text in the start and end of a string, before writing it to a .txt file

Can you try the following:

tempStr = '+URDFILE: "develop111.txt",606,"** ((content of local file)) OK'
tempStr = tempStr.strip()
if tempStr.startswith('+'):
    tempStr = tempStr[1:]
if tempStr.endswith('OK'):
    tempStr = tempStr[:-2]
print(tempStr)

Output:

URDFILE: "develop111.txt",606,"** ((content of local file))

If you want to select the required text then you can use regex for that. Can you try the following:

import re
tempStr = 'URDFILE: "develop111.txt",606,"** 01((content of local file)) OK'
tempStr = tempStr.strip()
if tempStr.startswith('+'):
    tempStr = tempStr[1:]
if tempStr.endswith('OK'):
    tempStr = tempStr[:-2]

# print(tempStr)
new_str = ''.join(re.findall(r'01(.+)', tempStr))
new_str = new_str.strip()
print(new_str)

Output:

((content of local file))

I assume that your URDFILE is always has the same return pattern +URDFILE: "filname",filesize,"filedata"\\nOK as it is AT command. So, it should be enough to ''.join(tempStr.split(',')[3:])[:-3]

Working example:

>>> s = '+URDFILE: "filname",filesize,"filedata, more data"\nOK' 
>>> ','.join(s.split(',')[2:])[:-3]
'"filedata, more data"' 

or to remove with quotes:

>>>','.join(s.split(',')[2:])[1:-4]
'filedata, more data'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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