python 中字符串中的特殊字符

special character in the string in python

我生成了一个字符串,如下所示,它是一个 df 表达式。

然而,当我添加另外两个变量时,我收到一个包含很多斜杠字符的字符串。使用 print 时它工作正常,但当我在第二种情况的函数中使用 return 字符串时它不起作用。你能告诉我吗

下面是正确生成的

str =  "{0}{1}.selectExpr('*',{2})".format(df,filter_feature,retrieved_features)

return str

"ptf_overall1.filter(ptf_overall1.measurement_group == 'test').selectExpr('*','case when email_14days > 0 then 1 else 0 end as journey_email_been_sent_flag','case when opened_14days > 0 then 1 else 0 end as journey_opened_flag')"

然而,当我尝试将以下两个字符串添加到现有字符串时,它会生成一个包含很多斜杠的字符串

print(group)

  .groupBy("country")

print(sum)

  .sum("email_14days")



str1 = "{0}{1}.selectExpr('*',{2}){3}{4}".format(df,filter_feature,retrieved_features,group,sum)



return str1
  
'ptf_overall1.filter(ptf_overall1.measurement_group == \'test\').selectExpr(\'*\',\'case when email_14days > 0 then 1 else 0 end as journey_email_been_sent_flag\',\'case when opened_14days > 0 then 1 else 0 end as journey_opened_flag\').groupBy("country").sum("email_14days")'

预期输出应该是

"ptf_overall1.filter(ptf_overall1.measurement_group == 'test').selectExpr('*','case when email_14days > 0 then 1 else 0 end as journey_email_been_sent_flag','case when opened_14days > 0 then 1 else 0 end as journey_opened_flag').groupBy("country").sum("email_14days")"

我尝试使用替换、重新和翻译。但是没有得到预期的输出。

我发现的解决方法如下。然而,这对我来说看起来很愚蠢。谁能在这里提出更好的解决方案。

query = print("{0}{1}.selectExpr('*',{2}){3}{4}".format(df,filter_feature,retrieved_features,group,sum))
  return  query

ptf_overall1.filter(ptf_overall1.measurement_group == 'test').selectExpr('*','case when email_14days > 0 then 1 else 0 end as journey_email_been_sent_flag','case when opened_14days > 0 then 1 else 0 end as journey_opened_flag').groupBy("country").sum("email_14days")