0

I am fairly new to python and was wondering how do you get a character in a string based on an index number?

Say I have the string "hello" and index number 3. How do I get it to return the character in that spot, it seems that there is some built in method that I just cant seem to find.

1
  • 1
    This is a very basic question. The answer can be easily here docs.python.org/2/tutorial You should read that before you do anything else Commented Mar 17, 2013 at 2:14

3 Answers 3

4

You just need to index the string, just like you do with a list.

>>> 'hello'[3]
l

Note that Python indices (like most other languages) are zero based, so the first element is index 0, the second is index 1, etc.

For example:

>>> 'hello'[0]
h
>>> 'hello'[1]
e
Sign up to request clarification or add additional context in comments.

2 Comments

not the best illustration because it doesn't make the origin obvious. Saying that [1] is e would be better
@PeterWooster The OP did ask for index number 3, so I just used that. I also mention that the indices were zero based, but just added some examples to make it clearer.
1

its just straight forward.

str[any subscript]. //e.g. str[0], str[0][0]

Comments

1

Check this page...

What you need is:

Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0.
There is no separate character type; a character is simply a string of size one.
Like in Icon, substrings can be specified with the slice notation: two indices separated by a colon.

Example:

>>> word[4]
'A'
>>> word[0:2]
'He'
>>> word[2:4]
'lp'

For your case try this:

>>> s = 'hello'
>>> s[3]
'l'

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.