python - 在python中提取子字符串

标签 python regex string-formatting

我想解析一个字符串以提取花括号中的所有子字符串:

'The value of x is {x}, and the list is {y} of len {}'

应该产生:

(x, y)

然后我想格式化字符串以打印带有值的初始字符串:

str.format('The value of x is {x}, and the list is {y} of len {}', x, y, len(y))

我该怎么做?

Example usage:
def somefunc():
    x = 123
    y = ['a', 'b']
    MyFormat('The value of x is {x}, and the list is {y} of len {}',len(y))

output:
    The value of x is 123, and the list is ['a', 'b'] of len 2

最佳答案

您可以使用 string.Formatter.parse :

Loop over the format_string and return an iterable of tuples (literal_text, field_name, format_spec, conversion). This is used by vformat() to break the string into either literal text, or replacement fields.

The values in the tuple conceptually represent a span of literal text followed by a single replacement field. If there is no literal text (which can happen if two replacement fields occur consecutively), then literal_text will be a zero-length string. If there is no replacement field, then the values of field_name, format_spec and conversion will be None.

from string import Formatter

s = 'The value of x is {x}, and the list is {y} of len {}'

print([t[1] for t in Formatter().parse(s) if t[1]])
['x', 'y']

不确定这对您尝试做的事情有何帮助,因为您可以在函数中将 x 和 y 传递给 str.format 或使用 **locals:

def somefunc():
    x = 123
    y = ['a', 'b']
    print('The value of x is {x}, and the list is {y} of len {}'.format(len(y),**locals()))

如果你想打印命名参数,你可以添加 Formatter 输出:

def somefunc():
    x = 123
    y = ['a', 'b']
    print("The named args are {}".format( [t[1] for t in Formatter().parse(s) if t[1]]))
    print('The value of x is {x}, and the list is {y} of len {}'.format(len(y), **locals()))

哪个会输出:

The named args are ['x', 'y']
The value of x is 123, and the list is ['a', 'b'] of len 2

关于python - 在python中提取子字符串,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30914010/

相关文章:

regex - 在 tcl 中使用正则表达式识别换行符

random - 如何随机选择格式字符串

python - 我将如何改善/使其运行更快?

python - 如何在 Dataframe 中删除最后一个不是 NaN 的值?

python - Django 和 Oracle DB 失去联系

python - Windows 7 上的 Tensorflow 安装错误

regex - 使用正则表达式过滤Google Analytics(分析)API-在字符前停止(查询字符串)

javascript - 来自 ReDos 攻击的安全正则表达式模式

java - 如何以日历格式打印数组中的值?

javascript - 如何使用变量名实现字符串格式化程序