【问题标题】:python write string to a file without quotespython将字符串写入不带引号的文件
【发布时间】:2016-11-29 03:30:38
【问题描述】:

我正在尝试将一些字符串写入文件但没有引号。

我正在读取列表并尝试将item[0] 写入输出文件。

我尝试映射并执行item[1:-1],但它们都不起作用。

这是我的代码:

for item in sorted(wrong_blocks):
      output.write(str(item[0]))

这会继续写入文件:

"word"

但我只想:

word

不带引号

我检查了这个 Python - how to write strings to file without quotes and spaces?

【问题讨论】:

  • 您的代码有语法错误。只是缺少括号,还是有更多内容被截断?
  • 现在是正确的
  • 你试过output.write(str(item[0])[1:-1])吗?
  • 是的,还是写引号
  • output.write(str(item[0]).strip('"'))?

标签: python string file


【解决方案1】:

您可以使用str.strip 从字符串的任一侧删除给定字符集的所有实例:

>>> s = '''"hello!"'''.strip('!"')
>>> print(s)
hello

将您的 output.write 呼叫更改为 output.write(str(item[0]).strip('"')),它将删除所有不需要的引号。

【讨论】:

  • 他的代码看起来是对的,但知道wrong_blocks 的内容将揭示sam_com 问题背后的真正原因。但是.strip('"') 在这种情况下真的不需要双引号也没什么坏处。
猜你喜欢
  • 2014-02-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-05-03
  • 2019-07-03
  • 1970-01-01
  • 2018-03-06
  • 1970-01-01
相关资源
最近更新 更多