首页 > 解决方案 > 将单引号添加到变量的值

问题描述

假设我们有一个变量 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

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

标签: python-3.xstringconcatenation

解决方案


你的意思是:

print(f"'{foo}'")

输出:

'text'

或者:

print(f'"{foo}"')

输出:

"text"

推荐阅读