python3: .strip( ) not working as expected [duplicate]

社会主义新天地 提交于 2020-01-30 10:48:06

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!