Is there any way to find out what is the nth character in a string using python?

Viewed 91

I'm making a currency converter in python and I would like to be able to find what the first character in a string is. By this I mean so if the user inputs the string "$32" my program can take out the first character, being "$", and recognise that the user would like to convert from dollars.

I'm sure this is possible in python but I cant figure out for the life of me how to do it, any help would be really appreciated, thanks.

4 Answers

Hope to be helpful for you. You can use val as number.

string = "$32"
first = string[0]
val = int(string[1:])
print(first, val)

In general the way to acess the nth character in a string is like this:

character = string[n]

So in your example use this:

string = "$32"
dollar = string[0]
three = string[1]
two = string[2]

Note that we start counting at 0.

The simplest solution was the use of slicing.

s = '$45'
curr, value = s[0], float(s[1:])

but I suggest to adopt some specific library to tackle with all combinations like price parser.

do this

actual = "$32"
value = float(actual[1:])
if actual[0] == "$":
    #do the converstion
Related