MUCHUAN SU
MUCHUAN SU

Reputation: 59

How to convert a single char in a sliced String into Integer in Python?

For example, I have a


String = "TGR1UK"

I only need the number 1 in the string to do some math operation so I make a number variable as


number = String[3]

but the type of this "number" is actually Char and I cant use

number = (int)String[3] 

to cast it into an integer

what should I do?

Upvotes: 0

Views: 321

Answers (2)

TheTechRobo
TheTechRobo

Reputation: 1384

You're using int wrong. int is used as follows:

int(string)

So, try number = int(String[3]).

Upvotes: 0

Aaron56
Aaron56

Reputation: 98

number = int(String[3])

This will cast it to an int. Read more here:

https://careerkarma.com/blog/python-string-to-int/

Edit: I have assumed when you said:

but the type of this "number" is actually Char and I cant use number = (int)String[3]

That you meant that wasnt working, because that is not how you cast to an int in python. Did you mean you aren't allowed to use a straight cast for some reason?

Upvotes: 1

Related Questions