【问题标题】:Adding single quotes to a value of a variable将单引号添加到变量的值
【发布时间】:2021-10-17 16:01:12
【问题描述】:

假设我们有一个变量 foo = "text" 。您将如何将其转换为 foo = '"text"' ?有没有办法在不使用库 urllib2 的情况下做到这一点?

编辑:下面是一个脚本:

def most_common(lst):
    if(len(lst) > 0):
        return max(set(lst), key=lst.count)
    else:
        return 0

test_list = list(df['a'])) # a is a column that can take the the values '"apple"', '"pear"', '"carrot"'

test_list_most = most_common(test_list) # returns "apple"

但假设我们要过滤数据框:

df = len(df[df['a'] == test_list_most].index) # length would be 0

这就是这个问题的上下文以及为什么我们要在双引号周围添加单引号。

【问题讨论】:

  • urllib2 的作用是什么?
  • foo = "text" 是 4 个字母 t e x t。你想要六个字母" t e x t "foo = '"text"' 怎么还不是答案?
  • >>> foo="'\"test\"'" >>> print(foo) '"test"'
  • 我认为答案是通过从 a 列中删除那些额外的引号来清理数据框:df['a'] = df['a'].str.slice(1, -1)。我还想知道 a 列是否真的有这些 qoutes,或者这是否只是熊猫在显示数据框时使用的 repr 表示。 print(df['a'][0]) 是否显示引号?

标签: python-3.x string concatenation


【解决方案1】:

在其周围添加双引号:'"' + foo + '"'。或者f'"{foo}"',如果您更喜欢格式字符串。

【讨论】:

    【解决方案2】:

    你可以这样转义字符

    print("'\"Hello World\"'")
    

    它会给出输出

    print("'\"Hello World\"'")
    

    或者当你需要分配给一个变量时

    foo = "'\"Hello World\"'"
    

    希望它能回答你的问题

    【讨论】:

      【解决方案3】:

      你的意思是:

      print(f"'{foo}'")
      

      输出:

      'text'
      

      或者:

      print(f'"{foo}"')
      

      输出:

      "text"
      

      【讨论】:

      • @DYZ 不清楚 OP 想要什么,无论如何我发布了可能的答案
      • @U11-Forward: 我要'"text"'
      • @timeinception23 - 由于 python 使用引号来分隔字符串,所以您一直让我们想知道您所说的“文本”是什么意思。是['"', 't', 'e', 'x', 't', '"']这6个字符吗?如果是这样,那么foo = '"text"' 已经是它了。我们要解决什么问题?
      • @tdelaney:如果你想过滤像 df = df[df['a'] == foo] 这样的 pandas 数据框,其中 'a' 是 df 的某个列,但 foo 应该是'“文本”'而不是“文本”。或者如果 foo = "apple",它应该是 '"apple"'。
      • @timeinception23 - 或者,您可以回答我非常具体的问题。 foo = '"Text"' 怎么不是正确答案?它是你如何得到你想要的 6 个字母的方式。
      猜你喜欢
      • 2020-03-02
      • 1970-01-01
      • 1970-01-01
      • 2017-09-06
      • 2017-12-17
      • 2011-07-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多