Is it possible to add int with str composed of text and numbers in Python?

3

I asked this question

And in the case of python ?

I can convert the string '1' str to 1 int .

Example:

1 + int('1') # Imprime: 2

However, if I try to convert '1 cachorro' str to int ...

int('1 cachorro');

... an error is generated:

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

Would it be possible to make expressions like 1 + int('1 cachorro') work in python ?

If I needed to do this (I think I'll never need it), how could I handle this?

    
asked by anonymous 21.08.2015 / 18:46

3 answers

4
  

Would it be possible to make expressions of type 1 + int('1 cachorro') work in python?

No. Or you add integers or concatenate strings . This is part of Python type security.

  

If I needed to do this (I think I'll never need it), how could I handle this?

The only reasonable operation would be the concatenation of strings . If you want to add an integer into a string in places where Python has located numbers - which would be the most exotic interpretation of your question - you would have to write your own function to do this, not would be using the sum operator.

    
21.08.2015 / 18:55
3

Your question already has a answer in the English version of StackOverflow!

The '+' operator works like this:

  • If the 2 operands are numbers: make the sum

  • Otherwise, concatenate strings.

If the string contains only numbers it can convert to integer .. otherwise it gives an exception.

So, in the code where you want to convert a string to int you should "wait" for an exception to happen.

string = "abcd"
try:
    i = int(string)
    print i
except ValueError:
    #Trata a exceção
    print 'a string não é um número'
    
21.08.2015 / 18:56
0

To do what you want, I think you can do the following:

int( re.search(r'\d+', '1cachorro).group() )

What this will do is pick up the string you put in, look up the integer, and return it. You can then use this value to make your sum.

    
21.08.2015 / 20:03