I have a file with text lines that I want to strip the first and last characters and then store the stripped lines in a list. The text is something like:
%5 sdgfjfhlsjf %5 %5 alkdregtrlkjdls %5 %5 dgglssj %5
In order to get rid of the leading and trailing characters (%5), I used the strip function in a few variants of code, but I didn't get the expected result. The leading characters are stripped, but the trailing ones are still in place:
sdgfjfhlsjf %5 alkdregtrlkjdls %5 dgglssj %5
This is code I try to implement at the moment:
stripped = []
with open ('/path/testfile') as file:
for line in file.readlines():
strippedline = line.strip("%5")
stripped.append(strippedline)
Can someone tell me what my mistake(s) is?
Thanks
CodePudding user response:
strip removes characters from both ends. In your case, the main issue though is that you have \n at the end of each line, so your code should remove that as well:
stripped = []
with open ('/path/testfile') as file:
for line in file.readlines():
strippedline = line.strip("\n%5")
stripped.append(strippedline)
