Python,一种更智能的字符串到整数转换方式 [英] Python, a smarter way of string to integer conversion

查看:101
本文介绍了Python,一种更智能的字符串到整数转换方式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已编写此代码以将格式为0(532)222 22 22的字符串转换为整数(例如05322222222)。

I have written this code to convert string in such format "0(532) 222 22 22" to integer such as 05322222222 .

class Phone():
    def __init__(self,input):
        self.phone = input
    def __str__(self):
        return self.phone
    #convert to integer.
    def to_int(self):
        return int((self.phone).replace(" ","").replace("(","").replace(")",""))

test = Phone("0(532) 222 22 22")
print test.to_int()

使用3种替换方法来解决这个问题感觉非常笨拙。我很好奇是否有更好的解决方案?

It feels very clumsy to use 3 replace methods to solve this. I am curious if there is a better solution?

推荐答案

p = "0(532) 222 22 22"
print ''.join([x for x in p if x.isdigit()])

请注意,如果要将其转换为int(如标题中所示),您将丢失前导零。如果你想这样做,只需将上面的内容包装在 int()调用中。虽然(在我看来)电话号码作为字符串更有意义。

Note that you'll "lose" the leading zero if you want to convert it to int (like you suggested in the title). If you want to do that, just wrap the above in a int() call. A telephone number does make more sense as a string though (in my opinion).

这篇关于Python,一种更智能的字符串到整数转换方式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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