Velja14
Velja14

Reputation: 3

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

Upvotes: 0

Views: 163

Answers (3)

user12842282
user12842282

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

knoepffler.net
knoepffler.net

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

Alexander Nied
Alexander Nied

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

Related Questions