【问题标题】:How to convert str to int and add them together?如何将 str 转换为 int 并将它们相加?
【发布时间】:2012-02-14 17:01:15
【问题描述】:

在过去的 2 个小时里,我一直在努力寻找解决方案,但一无所获。因此,要么这是不可能的,要么它是如此基础,以至于没有人写这个。基本上我有两个相等的数字的字符串,但是当我将它们加在一起时,我得到一个连接而不是数字..这是我的代码(Python)

currentNukeScriptName = nuke.root().name()
splitUpScriptName1 = currentNukeScriptName.split('/')
splitUpScriptName2 = splitUpScriptName1[-1]
splitScriptNameAndExtention = splitUpScriptName2.split('.')
currentNukeScriptName = splitScriptNameAndExtention[0]
splitUpCurrentScriptName = currentNukeScriptName.split('_')
currentVersionNumber = splitUpCurrentScriptName[-1]
decimalVersionNumber =  "1" + "," + str(currentVersionNumber)
addingNumber = 1
newVersionNumber = str(decimalVersionNumber) + str(addingNumber)

print newVersionNumber

decimaleVersionNumber = 1,019

如果我也更改 newVersionNumber 代码:

newVersionNumber = int(decimalVersionNumber) + int(addingNumber)

我明白了:

# Result: Traceback (most recent call last):
File "<string>", line 10, in <module>
ValueError: invalid literal for int() with base 10: '1,019'

我不确定该怎么做.. 这不可能吗?还是我做错了什么?

编辑:

所以问题是在我添加逗号的十进制版本号中发现的。保留逗号并仍然将数字相加的最佳方法是什么?

【问题讨论】:

    标签: python string int concatenation add


    【解决方案1】:
    ValueError: invalid literal for int() with base 10: '1,019'
    

    听起来它不喜欢逗号 - 先尝试删除它。

    【讨论】:

    • 我之前评论说它不起作用,但我想我错过了一些东西,因为它现在起作用了:S。你是对的..所以如果我想保留逗号我该怎么办?
    • 在解析整数之前将其删除(以编程方式)就可以了。除非你想弄乱locale 模块。
    【解决方案2】:

    你需要使用

    int.Parse(decimalVersionNumber) + int.Parse(addingNumber)
    

    这会将数字的字符串表示解析为整数,因此可以添加它们。

    例如:

    字符串连接:

    “10”+“20”=“1020”

    整数加法,从字符串中解析:

    int.Parse("10") + int.Parse("20") = 30

    【讨论】:

    • 我试过了,但它告诉我:# Result: Traceback (last recent call last): File "", line 10, in AttributeError: type object 'int' has没有属性“解析”
    • @user1159817:我想他以为你在用 C# 编写。
    • 啊,是的,我明白为什么了,当我第一次问这个问题时,我忘了标记 python
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2017-06-30
    • 1970-01-01
    • 2019-12-03
    • 2020-01-05
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多