Sw123
Sw123

Reputation: 67

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

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.

Upvotes: 1

Views: 986

Answers (4)

random_hooman
random_hooman

Reputation: 2218

do this

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

Upvotes: 0

Glauco
Glauco

Reputation: 1465

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.

Upvotes: 0

lionking-123
lionking-123

Reputation: 311

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

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

Upvotes: 2

CryptoNoob
CryptoNoob

Reputation: 161

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.

Upvotes: 1

Related Questions