17

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.

7
  • 3
    Strings are indexable just like lists. myString[5] will return the 6th character. Also, if for some reason you wanted to make it into a list anyways, list(myString) will make a list in the way you mention. Commented Aug 7, 2012 at 10:02
  • 1
    How about a[n] to get character number n? Commented Aug 7, 2012 at 10:02
  • both strings and lists are implemented using arrays. Commented Aug 7, 2012 at 10:08
  • 1
    You should work your way through the Python Tutorial docs.python.org/tutorial as it answers a lot of these questions. In particular docs.python.org/tutorial/introduction.html#strings will tell you all about subscripting and slicing strings. Commented Aug 7, 2012 at 10:20
  • also: my_str.index('c') is a method which will find the index of a substring. Commented Aug 7, 2012 at 10:26

3 Answers 3

29

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

>>> a = "fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"
>>> print a[10]
k
Sign up to request clarification or add additional context in comments.

Comments

5

Strings are iterable and indexable (since it is a sequence type), so you can just use:

"fkjdlfjzgjkdsheiwqueqpwnvkasdakpp"[10]

Comments

2

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'

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.