【问题标题】:Python remove space from string make it into intPython从字符串中删除空间使其变为int
【发布时间】:2016-10-20 18:43:57
【问题描述】:

如何删除<span id="balance">1 268</span> 中的空格并使其成为int

代码:

    Balance_afterWinORLoseBet.replace(" ", "")
    Balance_afterWinORLoseBet = int(balance_new.text) #Makes new var, turns it into int.


if "10.1" in countdown_timer.text: #
    Balance_afterPlaceBet.replace(" ", "")
    Balance_afterPlaceBet = int(balance_old.text) #Makes new var, turns it into int.

Error:

Balance_afterWinORLoseBet = int(balance_new.text) #生成新的var,将其转换为int。 ValueError: int() 以 10 为底的无效文字:'1 268'

【问题讨论】:

    标签: python python-2.7 python-3.x selenium


    【解决方案1】:

    其他答案均未解释您的代码为何不起作用。原因是.replace()没有改变原来的变量,而是返回"a copy of string s with all occurrences of substring old replaced by new"

    例子

    >>> Balance_afterWinORLoseBet = "1 268"
    >>> Balance_afterWinORLoseBet.replace(" ", "")
    '1268'
    >>> Balance_afterWinORLoseBet
    '1 268'
    

    【讨论】:

      【解决方案2】:

      我猜您希望最终输出为“1268”,并且不想将带有 HTML 标记的整个字符串转换为“int”类型。

      有了这个假设,你可以试试这个:

      myvar = '<span id="balance">1 268</span>' print int(myvar.replace(" ", "").split('>')[1].split('<')[0])

      【讨论】:

        【解决方案3】:

        您可能想试试这个。它适用于所有空白字符。

        int("".join(balance_new.text.split()))
        

        【讨论】:

          【解决方案4】:

          int(balance_new.text.replace(" ",""))

          【讨论】:

          • 强烈建议不要只回答代码。请添加一些关于代码正在做什么以及它如何回答问题的描述。另外,将您的代码格式化为代码。
          猜你喜欢
          • 2011-02-05
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2015-04-21
          • 2019-06-14
          • 2011-03-24
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多