I want to replace single quotes with double quotes in a list

前端 未结 3 426
一生所求
一生所求 2020-12-05 10:55

So I am making a program that takes a text file, breaks it into words, then writes the list to a new text file.

The issue I am having is I need the strings in the li

相关标签:
3条回答
  • 2020-12-05 11:23

    Most likely you'll want to just replace the single quotes with double quotes in your output by replacing them:

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

    You could also extend Python's str type and wrap your strings with the new type changing the __repr__() method to use double quotes instead of single. It's better to be simpler and more explicit with the code above, though.

    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"
    
    0 讨论(0)
  • 2020-12-05 11:31

    You cannot change how str works for list.

    How about using JSON format which use " for strings.

    >>> 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))
    
    0 讨论(0)
  • 2020-12-05 11:36

    In Python, double quote and single quote are the same. There's no different between them. And there's no point to replace a single quote with a double quote and vice versa:

    2.4.1. String and Bytes literals

    ...In plain English: Both types of literals can be enclosed in matching single quotes (') or double quotes ("). They can also be enclosed in matching groups of three single or double quotes (these are generally referred to as triple-quoted strings). The backslash () character is used to escape characters that otherwise have a special meaning, such as newline, backslash itself, or the quote character...

    "The issue I am having is I need the strings in the list to be with double quotes not single quotes." - Then you need to make your program accept single quotes, not trying to replace single quotes with double quotes.

    0 讨论(0)
提交回复
热议问题