简体   繁体   中英

Python: Finding the value of a character in a 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.

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

>>> a = "fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"
>>> print a[10]
k

字符串是可迭代和可索引的(因为它是序列类型 ),因此您可以使用:

"fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"[10]

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'

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM