'function to get nth letter from a string outputs number 1
when I try to get second character of string "hello" to get letter e it prints "1" for some reason
string = "hello"
print_string = string[2]
print(print_string)
I want to get the letter e or nth letter but I just get number 1
Solution 1:[1]
It's not printing a number 1; it is printing a lowercase letter "L", which is the third letter in the world "hello". Remember that Python is zero-indexed, so the first letter will be at index 0, and the second letter at index 1. Try:
string = "hello"
print_string = string[1]
print(print_string)
Solution 2:[2]
python is index-based, counting begins with zero:
string = "hello"
h e l l o\
0 1 2 3 4
use:
print(string[0])
to access "h"
or:
print(string[4])
to access "o"
it's not necessary to use an additional variable "print_string" in this case.
Solution 3:[3]
Here's another way of looking at it:
>>> for index, letter in enumerate("hello"):
... print (f'index={index} letter={letter}')
...
index=0 letter='h'
index=1 letter='e'
index=2 letter='l'
index=3 letter='l'
index=4 letter='o'
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Alexander Nied |
| Solution 2 | knoepffler.net |
| Solution 3 | Richard Dodson |
