将单引号添加到变量的值
Adding single quotes to a value of a variable
假设我们有一个变量 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
这就是这个问题的背景,以及为什么我们要在双引号周围添加单引号。
你的意思是:
print(f"'{foo}'")
输出:
'text'
或者:
print(f'"{foo}"')
输出:
"text"
加上双引号:'"' + foo + '"'
。或者 f'"{foo}"'
,如果您更喜欢格式字符串。
你可以这样转义字符
print("'\"Hello World\"'")
它将输出为
print("'\"Hello World\"'")
或者当你需要赋值给一个变量时
foo = "'\"Hello World\"'"
希望它能回答您的问题
假设我们有一个变量 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
这就是这个问题的背景,以及为什么我们要在双引号周围添加单引号。
你的意思是:
print(f"'{foo}'")
输出:
'text'
或者:
print(f'"{foo}"')
输出:
"text"
加上双引号:'"' + foo + '"'
。或者 f'"{foo}"'
,如果您更喜欢格式字符串。
你可以这样转义字符
print("'\"Hello World\"'")
它将输出为
print("'\"Hello World\"'")
或者当你需要赋值给一个变量时
foo = "'\"Hello World\"'"
希望它能回答您的问题