我正在使用 python 动态创建一个 jQuery 函数:
jQuery = ("$('%(other_id)').click(function() { "
" if ($(this).is(':checked')) { "
" $('%(text_id)').show() "
" } "
" else {"
" $('%(text_id)').hide()"
" }"
" });")
other_id
我必须在and中插入变量text_id
。我看到这个$
符号用于字符串模板(虽然不知道它是做什么的)所以我用 double $
-s( $$
)转义它们
jQuery = ("$$('%(other_id)').click(function() { "
" if ($$(this).is(':checked')) { "
" $$('%(text_id)').show() "
" } "
" else {"
" $$('%(text_id)').hide()"
" }"
" });")
但是我仍然无法格式化:
>>> choice_id = 'foo'
>>> text_choice_id = 'bar'
>>> jQuery = ("$$('%(other_id)').click(function() { "
" if ($$(this).is(':checked')) { "
" $$('%(text_id)').show() "
" } "
" else {"
" $$('%(text_id)').hide()"
" }"
" });")
>>> jQuery %{'other_id' : choice_id, 'text_id' : text_choice_id }
Traceback (most recent call last):
File "<pyshell#123>", line 1, in <module>
jQuery %{'other_id' : choice_id, 'text_id' : text_choice_id }
ValueError: unsupported format character ''' (0x27) at index 15
转义单引号后:
>>> jQuery = ("$$(\'%(other_id)\').click(function() { "
" if ($$(this).is(\':checked\')) { "
" $$(\'%(text_id)\').show() "
" } "
" else {"
" $$(\'%(text_id)\').hide()"
" }"
" });")
>>> jQuery %{'other_id' : choice_id, 'text_id' : text_choice_id }
Traceback (most recent call last):
File "<pyshell#125>", line 1, in <module>
jQuery %{'other_id' : choice_id, 'text_id' : text_choice_id }
ValueError: unsupported format character ''' (0x27) at index 15
无法尝试string.format()
,因为我在字符串中有括号。为什么我不断收到'
一些不受支持的格式字符?