【问题标题】:python list to .txt file, quotation marks disappearpython列表到.txt文件,引号消失
【发布时间】:2021-04-26 21:07:10
【问题描述】:

我有一个类似这样的 python 列表:

my_list = ["hello", "bye", "good morning", "good evening", , "'yes", "''no'"]

请注意,字符串中可能有一些奇怪的引号组合。

我想把它输出到一个文本文件中,但是在这个过程中引号会丢失。

我的代码:

with open('/foo/bar.txt', 'w') as writefile:
     writefile.write('\n'.join(my_list))

我的文本文件是这样的

hello
bye
good morning
...

我希望它看起来像这样:

"hello"
"bye"
"good morning"
...

【问题讨论】:

  • 你尝试过使用字符串字母

标签: python list txt


【解决方案1】:

一种可能的解决方案是使用字符串文字。无论您想在哪里使用这样的字符,只需在其前面放置一个“\”符号,或者为了更好地理解它,您可以阅读有关字符串文字here

my_list = ["\"hello\"", "bye", "good morning", "good evening", "'yes", "''no'"]

使用它也可以解决您的问题

【讨论】:

  • 您的方法是“硬编码”方法。目标是构建可重用的代码,这在任何方面都不灵活......此外,您将不得不更改数据并且您通常不想这样做
  • 我并不是说你错了,但人们也应该了解字符串文字和数据,我们可以使用正则表达式来修复所有在 2 中的所有内容,一个用于第一个引号,另一个用于另一个
【解决方案2】:

试试这个:

txt = ["hello", "bye", "good morning", "good evening", "yes", "no"]

with open("my_file.txt", "w") as f:
    f.writelines(f'"{w}"\n' for w in txt)

输出:

"hello"
"bye"
"good morning"
"good evening"
"yes"
"no"

【讨论】:

    【解决方案3】:

    引号仅在python语法中用于标记字符串。你可以这样写:

    with open('/foo/bar.txt', 'w') as writefile: 
        writefile.write('"' + ('"\n"'.join(mylist)) + '"')
    

    如果这不起作用,只需使用 for 循环将字符串与 f 字符串连接起来,瞧! :D

    【讨论】:

      猜你喜欢
      • 2013-09-20
      • 2016-10-24
      • 2023-04-11
      • 2022-07-28
      • 1970-01-01
      • 2015-12-13
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多