python123子字符串输出_在python中提取子字符串

你可以使用

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()))

如果要打印命名的args,可以添加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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值