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

While working as a researcher in distributed systems, Dr. Christian Mayer found his love for teaching computer science students.
To help students reach higher levels of Python success, he founded the programming education website Finxter.com that has taught exponential skills to millions of coders worldwide. He’s the author of the best-selling programming books Python One-Liners (NoStarch 2020), The Art of Clean Code (NoStarch 2022), and The Book of Dash (NoStarch 2022). Chris also coauthored the Coffee Break Python series of self-published books. He’s a computer science enthusiast, freelancer, and owner of one of the top 10 largest Python blogs worldwide.
His passions are writing, reading, and coding. But his greatest passion is to serve aspiring coders through Finxter and help them to boost their skills. You can join his free email academy here.