Pythonic方法将字符串中的所有八进制值评估为整数 [英] Pythonic way to eval all octal values in a string as integers

查看:70
本文介绍了Pythonic方法将字符串中的所有八进制值评估为整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

例如,我有一个字符串,例如 012 + 2-01 + 24 。我希望能够快速(更少的代码)评估该表达式...

So I've got a string that looks like "012 + 2 - 01 + 24" for example. I want to be able to quickly (less code) evaluate that expression...

我可以在字符串上使用eval(),但是我不希望 012 以八进制形式(10)表示,我希望将其表示为int(12)。

I could use eval() on the string, but I don't want 012 to be represented in octal form (10), I want it to be represented as an int (12).

我对此的解决方案有效,但并不优雅。我有点假设有一种非常好的pythonic方式可以做到这一点。

My solution for this works, but it is not elegant. I am sort of assuming that there is a really good pythonic way to do this.

我的解决方案:

#expression is some string that looks like "012 + 2 - 01 + 24"
atomlist = []
for atom in expression.split():
    if "+" not in atom and "-" not in atom:
        atomlist.append(int(atom))
    else:
        atomlist.append(atom)
#print atomlist
evalstring = ""
for atom in atomlist:
    evalstring+=str(atom)    
#print evalstring
num = eval(evalstring)

基本上,我撕开字符串,找到其中的数字并将其转换为整数,然后重建字符串带有整数(基本上除去前导0,除非0本身是数字)。

Basically, I tear appart the string, and find numbers in it and turn them into ints, and then I rebuild the string with the ints (essentially removing leading 0's except where 0 is a number on its own).

如何更好地做到这一点?

How can this be done better?

推荐答案

我很想使用正则表达式删除前导零:

I'd be tempted to use regular expressions to remove the leading zeroes:

>>> re.sub(r'\b0+(?!\b)', '', '012 + 2 + 0 - 01 + 204 - 0')
'12 + 2 + 0 - 1 + 204 - 0'

这会删除每个数字开头的零,除非数字完全由零组成:

This removes zeroes at the start of every number, except when the number consists entirely of zeroes:


  • 第一个 \b 匹配单词(令牌)边界;
  • 0 + 匹配一个或多个连续零;

  • (?!\b) 负前瞻 )禁止匹配,其中零序列后面是标记边界。

  • the first \b matches a word (token) boundary;
  • the 0+ matches one or more consecutive zeroes;
  • the (?!\b) (negative lookahead) inhibits matches where the sequence of zeroes is followed by a token boundary.

此方法相对于<基于code> split()的替代方法是它不需要空格即可工作:

One advantage of this approach over split()-based alternatives is that it doesn't require spaces in order to work:

>>> re.sub(r'\b0+(?!\b)', '', '012+2+0-01+204-0')
'12+2+0-1+204-0'

这篇关于Pythonic方法将字符串中的所有八进制值评估为整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆