【问题标题】:Python: Extract parts of a string somehow got pushed down to a new linePython:提取字符串的一部分以某种方式被推到新行
【发布时间】:2017-12-09 16:56:24
【问题描述】:

我使用此代码来提取 html 的最后“/”之后的部分。我想在链接本身之后有那个分区,用逗号分隔。但是,在输出文件中,分区总是被下推到一个新行,而不是连续连接到关联的链接行。

 with open('links_parts.txt', mode='wt') as outfile:
   for link in file_to_set('links.txt'):
     path_parts = link.rpartition('/')[2]
     outfile.write(link + ','+ path_parts + '\n')

【问题讨论】:

  • 尝试打印你的变量......也许它会给你一个关于发生了什么以及如何进行的线索......
  • 什么返回file_to_set
  • 尝试在您的文本字符串上运行strip()Tutorial
  • 我试过 strip() 但没用。
  • 啊,好吧,我想我找到了问题所在。 strip() 必须在我进行分区之前完成。谢谢!!

标签: python string partition


【解决方案1】:

那是因为link 是一行,因此有一个尾随的换行符,您需要使用str.rstrip 去除它:

for link in file_to_set('links.txt'):
    link = link.rstrip()
    path_parts = link.rpartition('/')[2]
    outfile.write(link + ',' + path_parts + '\n')

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-03-28
    • 2015-12-31
    • 1970-01-01
    • 1970-01-01
    • 2020-12-18
    相关资源
    最近更新 更多