1.9 KiB
Concepts of reverse-string
Example implementation:
From the current example.py:
def reverse(text: str = "") -> str:
"""Reverse a given string"""
return text[::-1]
Concepts
-
[Function][function]:
defto create a function in Python -
[Immutability][immutability]:
textstr in Python is immutable. In this exercise, you return a new string, the old stringtextis not changed. -
[Return Value][return-value]: this function return a string by this line:
return text[::-1] -
[Slicing][slicing]: because
strin Python is a sequence type, slicing syntax can be used here. Specifically: for syntaxstring[start:stop:stride]:start: 0-index of the start position,start=0by default (i.e., not specified) (start from the beginning)stop: 0-index of the stop position,stop=-1by default (i.e., not specified) (stop at the end)stride: number of skip step. For example,>>> string = 'ABCDEF'[::2] >>> print(string) 'ACE'- In this exercise,
stride = -1means start from the end Together effectively, slicing of[::-1]gives the reversed string Extra material for string slicing.
-
[Docstrings][docstrings]: used to document the function, normally situated right below
def func(): -
[Type hinting][type-hinting]: In modern Python it's possibly to type hint annotations to parameters and variables, see typing. While not necessary in Python such annotations can help your code be easier to read, understand, and check automatically using tools like
mypy.