Texts consist of characters and sometimes it’s necessary to perform operations on individual characters. In python, we can access individual characters through the index operator []:
greeting = 'Welcome to indexing!'
print(greeting[0]) # W
print(greeting[1]) # e
print(greeting[2]) # l
print(greeting[3]) # c
Every character is in itself a string. So, we can operate with characters exactly as strings. We can concatenate them with +, we can multiply them by a number to repeat them several times, etc.
Notice that the indexing starts from 0. To access the first letter we do it with [0], to access the second one - [1], the third one - [2], etc. Python uses 0-based indexing. It’s a well-established practice in different programming languages (C++, Java, C#, etc) and many languages follow 0-based indexing as well.
# 01234
greeting = 'hello'
print(greeting[0]) # h
print(greeting[4]) # o
print(len(greeting)) # 5 (there are 5 characters)
print(greeting[len(greeting) - 1]) # o (therefore, we access the 5th with [4])
print(greeting[len(greeting) - 2]) # l
Challenge
Given the following text, your task is to determine the n-th character of the text:
In 2017, Bitcoin reached ~$20k. People thought it was the historical maximum.
The input contains a single integer n. Print the character of the given sentence at the n-th position (the counting starts from 1). If n is not within 1...text-length, the program should output Bad Input.