相关疑难解决方法(0)

将字符串转换或取消格式化为Python中的变量(如format(),但反之)

我有形式的字符串Version 1.4.0\nVersion 1.15.6\n,我想从他们身上抽取三个数字的简单方法.我知道我可以使用format方法将变量放入字符串中; 我基本上想要倒退,像这样:

# So I know I can do this:
x, y, z = 1, 4, 0
print 'Version {0}.{1}.{2}\n'.format(x,y,z)
# Output is 'Version 1.4.0\n'

# But I'd like to be able to reverse it:

mystr='Version 1.15.6\n'
a, b, c = mystr.unformat('Version {0}.{1}.{2}\n')

# And have the result that a, b, c = 1, 15, 6
Run Code Online (Sandbox Code Playgroud)

我找到的其他人问了同样的问题,但回复是针对他们的特定情况的: 反向使用Python格式字符串进行解析

一般答案(如何format()反向)会很棒!我的具体案例的答案也会非常有用.

python string-formatting

28
推荐指数
4
解决办法
1万
查看次数

标签 统计

python ×1

string-formatting ×1