Daily Python Puzzle: String Indexing

What is the output of this code snippet?


x = 'silent'
print(x[2] + x[1] + x[0]
      + x[5] + x[3] + x[4])


This puzzle introduces a powerful tool for your Python toolbox. Make sure, you feel comfortable using it because many advanced puzzles depend on it. The name of the tool is indexing.

In Python, you can access every character in the string by using an integer value which defines the position of the character in the string. We call this integer value an index.

If the string has 5 characters like in the example, the indices of these characters are as follows.

String s:    s  i  l  e  n  t
Index:        0 1  2 3  4 5

You can index any character using the square bracket notation ‘[]’ with their respective position values. For example, the indexing ‘s[2]’ would return the character ‘l’.

The plus operator ‘+’ is context sensitive. It calculates the mathematical sum for two given numerical values but appends strings for two given string values. For example, appending two strings ‘a’ + ‘b’ returns the new string ‘ab’.

With this information, you are now able to determine how the string s is reordered using indexing notation and the ‘+’ operator for strings.

A small note in case you were confused. There is no separate character type; a character is a string of size one.

Are you a master coder?
Test your skills now!


Related Video




Leave a Comment