Python从字符串中删除空格将其转换为int

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

如何删除 <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) #Makes new var, turns it into int. ValueError: invalid literal for int() with base 10: '1 268'

最佳答案

其他答案都没有解释为什么您的代码不起作用。原因是.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'

关于Python从字符串中删除空格将其转换为int,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37906790/

相关文章:

Python 字典问题。如何对相似的字符串进行分组?

python - 当 DEBUG = False 时如何在 Django 2.* 中提供静态文件?

python-3.x - Pydev 显示 Unresolved 导入,但脚本运行?

python - 获取目录中所有文件名的列表及其原始文件夹顺序

python - 选择 QListView 中的所有项目并在目录更改时取消选择所有项目

python - 在Python中,如何使用super作为类属性?

python - 创建元组的子类时调用 __new__

python - 如何使用 Python 中的日志打印列表项 + 整数/字符串

python - 在 Python 中对字符串进行编码

python - 在 Python 中对一系列日期进行分组