【问题标题】:converting string with Apostrophes to long (not int)将带撇号的字符串转换为 long(不是 int)
【发布时间】:2015-03-18 18:41:43
【问题描述】:

如何将带有此字符串“70”(带有撇号)的字符串转换为长字符串

代码:

 gap = long(x.film_index)-   long (expected_film)

错误:ValueError: invalid literal for long() with base 10: '"70"'

【问题讨论】:

  • 你试过只删除帖子吗? long(x.film_index.strip('"'))?
  • 另请注意 long 在 3.x 中消失了,在 2.x 或 3.x 中使用 int 并没有什么害处,因为在 2.x 中它会自动转换为long 需要的地方。
  • 同样的错误:ValueError: int() 以 10 为底的无效文字:'"70"'
  • 仍然没有帮助 gap = (x.film_index.strip('"'))- (expected_film.strip('"')) AttributeError: 'int' object has no attribute 'strip'
  • 那么其中一个已经是 int 而不是字符串...type(x.film_index), type(expected_film) 向您展示了什么?

标签: python python-2.7


【解决方案1】:

strip 在转换前去掉引号。

>>> x = "\"70\""
>>> long(x.strip("\""))
70L

【讨论】:

    【解决方案2】:

    您可以使用正则表达式从给定字符串中仅提取数字:

    import re
    long(re.match(r'\d+', '"70"').group())
    

    但是,如果您知道您的号码将始终"s 包围,那么您可以轻松地从中构造一个新的int,而无需第一个和最后一个字符:

    long('"70"'.strip('"'))  # or long('"70"'.replace('"', ''))
    

    【讨论】:

      【解决方案3】:

      先用replace()去掉引号怎么样?

      >>> x = '"70"'
      >>> x
      '"70"'
      >>> long(x)
      Traceback (most recent call last):
        File "<stdin>", line 1, in <module>
      ValueError: invalid literal for long() with base 10: '"70"'
      
      >>> long(x.replace('"', ''))
      70L
      

      【讨论】:

      • 谢谢,我想我会使用这个选项
      猜你喜欢
      • 1970-01-01
      • 2011-02-14
      • 1970-01-01
      • 1970-01-01
      • 2016-04-06
      • 2014-06-08
      • 2023-02-15
      • 2019-05-05
      • 2020-12-02
      相关资源
      最近更新 更多