Python中的转义和引号

时间:2019-04-30 03:06:47

标签: python python-3.x string replace

我想做的是将转义符放在python字符串中。让我解释一下。

我有字串

library(dplyr)
library(tidyr)

# First Portion
df_DATE <- df %>% 
  group_by(ID) %>% 
  mutate(DATE = dmy(DATE),
         RANK_DATE = dense_rank(DATE)) %>% 
  group_by(ID, RANK_DATE) %>% 
  filter(RANK_DATE %in% 1:2,
         row_number() == n()) %>% 
  ungroup() %>% 
  mutate(DATE = as.character(DATE)) %>% 
  gather(VARIABLE, VALUE, -c(ID, RANK_DATE)) %>% 
  unite(VARIABLE, VARIABLE, RANK_DATE) %>% 
  spread(VARIABLE, VALUE) %>% 
  select(ID, 
         FIRST_DATE = DATE_1, FIRST_RESULT = RESULT_1, 
         SECOND_DATE = DATE_2, SECOND_RESULT = RESULT_2)

# Second Portion
df_RESULT <- df %>%
  group_by(ID) %>% 
  mutate(DATE = dmy(DATE),
         RANK_RESULT = row_number(RESULT)) %>% 
  filter(RANK_RESULT %in% 1:2) %>% 
  mutate(DATE = as.character(DATE)) %>% 
  gather(VARIABLE, VALUE, -c(ID, RANK_RESULT)) %>% 
  unite(VARIABLE, VARIABLE, RANK_RESULT) %>% 
  spread(VARIABLE, VALUE) %>% 
  select(ID, 
         LOWEST_DATE = DATE_1, LOWEST_VALUE = RESULT_1, 
         SECOND_LOWEST_DATE = DATE_2, SECOND_LOWEST_VALUE = RESULT_2)

# Combine the 2 portions
df_out <- full_join(df_DATE, df_RESULT)

然后将此str = 'station and the "Tren Bach"' 格式化为大的“ SQL”查询,由于“ Tren Bach”中间的双引号引起str

所以我尝试在进行如下格式化之前进行预处理。

malformed exception

但是在sql字符串中,转义不存在。

第二次,我尝试过

str = str.replace ('"', '\"')
sql.format(str)

但是此时,SQL中显示了两次转义。

预期如下。

str = str.replace ('"', '\\"')
sql.format (str)

这样str = 'station and the \"Tren Bach\"' 不会在sql语句中造成麻烦。

您会建议其他方式吗?

1 个答案:

答案 0 :(得分:0)

BigQuery使用slightly different escaping,然后使用标准SQL。与Python类似,您需要在查询中用引号将值引起来。例如:

s = '''SELECT ... WHERE my_field='station and the "Tren Bach"' '''
#               note quotes here ^                  and here ^