String Indexing in Python (2-Min Tutorial)

What is the output of this code snippet?

[python]
x = ‘silent’
print(x[2] + x[1] + x[0]
+ x[5] + x[3] + x[4])
[/python]

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 concatenate 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

Solution

listen

Leave a Comment