Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: Finding the value of a character in a string

Tags:

python

string

Given a long string such as:

"fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"

or

"0.53489082304804918409853091868095809846545421135498495431231"

How do I find the value of the nth character in that string? I could solve this if I could convert it into a list (where each digit gets it's own index) but since the numbers aren't separated by commas I don't know how to do this either.

AFAIK there is no command like string.index(10) which would return the 11th character in.

like image 587
Ribilla Avatar asked Aug 07 '12 10:08

Ribilla


People also ask

How do I find the value of a character in a string in Python?

To find the ASCII value of a character, we can use the ord() function, which is a built-in function in Python that accepts a char (string of length 1) as argument and returns the unicode code point for that character.

How do you extract a character from a string in Python?

You can extract a substring in the range start <= x < stop with [start:step] . If start is omitted, the range is from the beginning, and if end is omitted, the range is to the end. You can also use negative values. If start > end , no error is raised and an empty character '' is extracted.

How do I find a character in a string?

The strchr() function finds the first occurrence of a character in a string. The character c can be the null character (\0); the ending null character of string is included in the search. The strchr() function operates on null-ended strings.


2 Answers

strings are like lists. so you can access them the same way,

>>> a = "fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"
>>> print a[10]
k
like image 130
Inbar Rose Avatar answered Oct 27 '22 00:10

Inbar Rose


To get the corresponding character in the nth value, just use this function:

def getchar(string, n):
    return str(string)[n - 1]

Example usage:

>>> getchar('Hello World', 5)
'o'
like image 26
Richie Bendall Avatar answered Oct 26 '22 23:10

Richie Bendall