簡體   English   中英

我想用列表中的雙引號替換單引號

[英]I want to replace single quotes with double quotes in a list

所以我正在制作一個程序,它接受一個文本文件,將其分解為單詞,然后將列表寫入一個新的文本文件。

我遇到的問題是我需要列表中的字符串是雙引號而不是單引號。

例如

當我想要這個["dog","cat","fish"]['dog','cat','fish']我得到這個['dog','cat','fish'] ["dog","cat","fish"]

這是我的代碼

with open('input.txt') as f:
    file = f.readlines()
nonewline = []
for x in file:
    nonewline.append(x[:-1])
words = []
for x in nonewline:
    words = words + x.split()
textfile = open('output.txt','w')
textfile.write(str(words))

我是python的新手,並沒有發現任何關於這一點。 有誰知道如何解決這個問題?

[編輯:我忘了提到我在arduino項目中使用輸出,要求列表有雙引號。]

您無法更改strlist

如何使用"用於字符串的JSON格式 "

>>> animals = ['dog','cat','fish']
>>> print(str(animals))
['dog', 'cat', 'fish']

>>> import json
>>> print(json.dumps(animals))
["dog", "cat", "fish"]

import json

...

textfile.write(json.dumps(words))

很可能你只想用輸出中的雙引號替換單引號:

str(words).replace("'", '"')

您還可以擴展Python的str類型和新的類型改變包裝你的字符串__repr__()用雙引號,而不是單一的方法。 不過,最好使用上面的代碼更簡單,更明確。

class str2(str):
    def __repr__(self):
        # Allow str.__repr__() to do the hard work, then
        # remove the outer two characters, single quotes,
        # and replace them with double quotes.
        return ''.join(('"', super().__repr__()[1:-1], '"'))

>>> "apple"
'apple'
>>> class str2(str):
...     def __repr__(self):
...         return ''.join(('"', super().__repr__()[1:-1], '"'))
...
>>> str2("apple")
"apple"
>>> str2('apple')
"apple"

在Python中,雙引號和單引號是相同的。 他們之間沒有什么不同。 用雙引號替換單引號是沒有意義的,反之亦然:

2.4.1。 字符串和字節文字

...用簡單的英語:兩種類型的文字都可以用匹配的單引號(')或雙引號(“)括起來。它們也可以用三個單引號或雙引號的匹配組括起來(這些通常被稱為三元組) - 帶字符串)。反斜杠()字符用於轉義具有特殊含義的字符,例如換行符,反斜杠本身或引號字符......

“我遇到的問題是我需要列表中的字符串是雙引號而不是單引號。” - 然后你需要讓你的程序接受單引號,而不是試圖用雙引號替換單引號。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM