user1159817
user1159817

Reputation: 29

How to convert str to int and add them together?

I've spent the last 2 hours trying to find a solution for this and came up with nothing. So either this is not possible or its so basic that no one write about this. Basically I have 2 strings that both equal numbers, but when I go to add them together I get a concatenate instead of a number.. here is my code (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

If I change the newVersionNumber code too:

newVersionNumber = int(decimalVersionNumber) + int(addingNumber)

I get:

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

I am unsure what to do.. Is this not possible? Or am I doing something totally wrong?

Edit:

So the problem was found in the decimalVersionNumber where I was adding a comma. What would be the best way of keeping the comma and still adding the numbers together?

Upvotes: 1

Views: 2663

Answers (2)

Simon Bridge
Simon Bridge

Reputation: 1346

You need to use

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

This will parse the string representation of the numbers into integers, so they can be added.

eg:

String concatenation:

"10" + "20" = "1020"

Integer addition, parsed from strings:

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

Upvotes: 0

James M
James M

Reputation: 16718

ValueError: invalid literal for int() with base 10: '1,019'

Sounds like it doesn't like the comma - try removing it first.

Upvotes: 6

Related Questions