【问题标题】:New style format specifier throwing tokenization error新样式格式说明符引发标记化错误
【发布时间】:2018-10-02 06:50:45
【问题描述】:

我在变量 jss 中有以下字符串。

jss = '''
Java.perform(
  function()
  {
    var item = Java.use("java.util.Random"); 
    console.log("HOOKING random");
    item.nextInt.overload("int").implementation = function(a)
    {
      var ret = this.nextInt(a); 
      return {0};
    }
  }
);
'''.format("1234")

我正在尝试使用格式说明符来简单地传递一些值(在本例中为“1234”)。

当我尝试在 iPython 中运行它时,我收到以下错误:

ERROR:root:An unexpected error occurred while tokenizing input
The following traceback may be corrupted or invalid
The error message is: ('EOF in multi-line string', (1, 0))

---------------------------------------------------------------------------
KeyError                                  Traceback (most recent call last)
<ipython-input-1-a900f760c449> in <module>()
     12   }
     13 );
---> 14 '''.format("1234")

KeyError: '\n    var item = Java'

不确定这里出了什么问题。有人可以帮忙理解吗?

【问题讨论】:

    标签: string python-2.7 string-formatting format-specifiers


    【解决方案1】:

    您需要使用 {{}} 转义其他大括号 - 否则 python 格式标记器想要理解该模式。 (仅在python3中测试...)

    jss = '''
    Java.perform(
      function()
      {{
        var item = Java.use("java.util.Random"); 
        console.log("HOOKING random");
        item.nextInt.overload("int").implementation = function(a)
        {{
          var ret = this.nextInt(a); 
          return {0};
        }}
      }}
    );
    '''.format("1234")
    

    假设您不想用作格式化选项的大括号前面总是有多个空格(格式大括号前面最多有一个空格),您可以替换它们:

    import re 
    
    # with your original jss
    sanitized = re.sub('(\s\s+){', r'\1{{', jss)
    sanitized = re.sub('(\s\s+)}', r'\1}}', sanitized)
    
    print(sanitized.format("1234"))
    

    ...可能有更明智的正则表达式来满足您的需求...

    【讨论】:

    • 太棒了。感谢那。做我的工作!
    猜你喜欢
    • 1970-01-01
    • 2017-11-16
    • 1970-01-01
    • 2012-10-01
    • 2016-02-13
    • 2013-08-28
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多