问题
I am parsing a file and want to strip the word Energy from the lines of the file but using .strip("Energy")
doesn't yield the desired result and removed the 'E' of the 'Epoch'. I am probably not using the data types correctly or don't understand .strip()
correctly. Please explain why am I getting the output given at the end of this post.
I have a file which looks like :
Epoch [20/20], Step 1,[1/3000], Loss: 7.2197, Energy: 0.2414, Prediction:-2.4456
Epoch [20/20], Step 2,[2/3000], Loss: 0.6216, Energy: -0.2094, Prediction:0.5790
and I pass it through the following code in a jupyter notebook
with open(out_file) as f:
for i in f:
if i.startswith("Epoch"):
row=str(i)
print(row.strip("Energy")) # notice this line
which gives me the following output :
poch [20/20], Step 1,[1/3000], Loss: 7.2197, Energy: 0.2414, Prediction:-2.4456
poch [20/20], Step 2,[2/3000], Loss: 0.6216, Energy: -0.2094, Prediction:0.5790
回答1:
str.strip()
docs: “Return a copy of the string S with leading and trailing whitespace removed. If chars is given and not None, remove characters in chars instead.”. So it strips all E
, n
, e
, r
, g
, and y
characters from both ends. In your case the E
from Epoch
, but not the next p
and not the digits from the end.
You can do:
if i.startswith('Energy'):
print(i[6:])
to remove Energy
from the beginning.
来源:https://stackoverflow.com/questions/57393390/python3-strip-not-working-as-expected