小编hac*_*ime的帖子

如何从python字符串中获取命名变量的名称

有没有一种优雅的方法来获取%s字符串对象的命名类变量的名称?像这样:

string = '%(a)s and %(b)s are friends.'
names = get_names(string)  # ['a', 'b']
Run Code Online (Sandbox Code Playgroud)

已知的替代方式:

  1. 使用正则表达式解析名称,例如:

    import re
    names = re.findall(r'%\((\w)\)[sdf]', string)  # ['a', 'b']
    
    Run Code Online (Sandbox Code Playgroud)
  2. 使用.format()兼容的格式和Formatter().parse(string).

    如何从format()方法的字符串中获取变量名称

但是具有%s类变量的字符串怎么样?

PS:python 2.7

python string-interpolation

8
推荐指数
1
解决办法
182
查看次数

标签 统计

python ×1

string-interpolation ×1