Python strip 函数仅适用于字符串的左侧

发布于 2025-01-20 11:34:41 字数 504 浏览 3 评论 0原文

我有一个文本行的文件,我想剥离第一个和最后一个字符,然后将剥离的行存储在列表中。文本类似于:

%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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

凹づ凸ル 2025-01-27 11:34:41

strip 删除两端的字符。就您而言,主要问题是每行末尾都有 \n ,因此您的代码也应该删除它:

stripped = []        
with open ('/path/testfile') as file:
    for line in file.readlines():
        strippedline = line.strip("\n%5")
        stripped.append(strippedline)

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)
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文