【问题标题】:How to edit the string and add quotes in python [closed]如何在python中编辑字符串并添加引号[关闭]
【发布时间】:2021-10-06 07:31:50
【问题描述】:

我在 python 上遇到了拆分字符串的问题。例如,我有一个字符串需要在其上添加一些引号。

示例字符串:

word = "VITAMIN, HEALTH, SPORT"

并对其进行编辑以在其上添加一些引号,如下所示

word = "'VITAMIN', 'HEALTH', 'SPORT'"

【问题讨论】:

    标签: python string split


    【解决方案1】:

    只要做:

    word = ", ".join(f"'{s}'" for s in word.split(", "))
    print(word)
    

    输出

    'VITAMIN', 'HEALTH', 'SPORT'
    

    【讨论】:

      【解决方案2】:

      用途:

      str(word.split(", "))[1:-1]
      

      或者干脆做:

      "'" + "', '".join(word.split(', ')) + "'"
      

      两种解决方案的输出:

      'VITAMIN', 'HEALTH', 'SPORT'
      

      str.splitstr 一起使用,然后切片以删除括号。

      【讨论】:

        【解决方案3】:

        您需要使用\' 转义引号。 所以你的代码将是 -

        word = "\'VITAMIN\', \'HEALTH\', \'SPORT\'"
        

        关于转义字符的文章 https://www.w3schools.com/python/gloss_python_escape_characters.asp

        【讨论】:

          【解决方案4】:

          使用str.__repr__ 将字符串放在单引号内这一事实的一种方法(除非字符串包含单引号):

          word = ", ".join(map(repr, word.split(", ")))
          

          文档:

          【讨论】:

            猜你喜欢
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2012-09-18
            • 2011-05-24
            • 1970-01-01
            • 1970-01-01
            • 2021-11-30
            相关资源
            最近更新 更多