Python strip 函数仅适用于字符串的左侧
我有一个文本行的文件,我想剥离第一个和最后一个字符,然后将剥离的行存储在列表中。文本类似于:
%5 SDGFJFHLSJF%5 %5 alkdregtrlkjdls%5 %5 dgglssj%5
为了摆脱领先和尾随的字符(%5),我在几种代码中使用了剥离功能,但我没有得到预期的结果。领导角色被剥离,但尾随的角色仍然存在:
SDGFJFHLSJF%5 alkdregtrlkjdls%5 DGGLSSJ%5
这是我目前尝试实现的代码:
stripped = []
with open ('/path/testfile') as file:
for line in file.readlines():
strippedline = line.strip("%5")
stripped.append(strippedline)
有人可以告诉我我的错误是什么?
谢谢
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
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
strip
删除两端的字符。就您而言,主要问题是每行末尾都有\n
,因此您的代码也应该删除它:strip
removes characters from both ends. In your case, the main issue though is that you have\n
at the end of eachline
, so your code should remove that as well: