Reputation: 3
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
Upvotes: 0
Views: 163
Reputation:
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'
Upvotes: 1
Reputation: 71
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.
Upvotes: 1
Reputation: 13623
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)
Upvotes: 1