【问题标题】:Convert List to Int with Python使用 Python 将 List 转换为 Int
【发布时间】:2014-07-23 13:58:45
【问题描述】:

我已经在这里复习了几个问题来做到这一点,但没有运气。

我正在尝试将变量 phone_numberslist 转换为 int,以便将其正确插入数据库列 INT(10),例如8881112222

我目前有:

phone_numbers = toasted_tree.xpath('//b/text()')
#convert phone number 888-111-2222 to 8881112222
for phone_number in phone_numbers:
    phone_number = phone_number.replace('-', '').replace('','')
    print phone_number

这输出没有- 的数字就好了。

问题是,我希望这些值是 int 形式,我仍然相信它们是 list 形式(只是没有破折号,我该怎么做?

【问题讨论】:

  • .replace('','') 的意义何在?

标签: python xpath int type-conversion


【解决方案1】:

由于xpath() 返回一个字符串列表并且您应用.replace() - phone_number 绝对是一个字符串,您可以使用int() 将其转换为int

phone_number = int(phone_number)

如果xpath() 调用只返回一个项目,则只需获取第一个元素:

phone_number = toasted_tree.xpath('//b/text()')[0]
phone_number = int(phone_number.replace('-', ''))

【讨论】:

  • 这里非常彻底。非常感谢@alecxe!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2018-04-28
  • 2014-11-08
  • 2013-01-01
  • 1970-01-01
  • 2016-12-26
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多