Corsi registrati su
Corsi in diretta per la formazione di Front End Developer e Back End Developer
In this lesson we will cover strings in Python. To declare a variable of type string just assign it a text enclosed in single quotes or double quotes. So let’s take an example:
>>>phrase = ‘Coding creativo’
or, in the same way:
>>>phrase = “Coding creativo”
String operators in Python
+ string concatenation.
*repetition of a string (must be followed or preceded by a numeric value).
First example with strings in Python
If we then use the + operator:
>>> phrase = ‘Hello’
>>> phrase_2 = ‘ everyone.’
>>> phrase + phrase_2
output: Hello everyone.
In this case we have concatenated the two strings. While if we use the operator *:
In this example we have obtained a repetition of the phrase Hello, based on the numerical value specified after the operator.
The len() function is used to find out the length of the string. Therefore:
>>> phrase = ‘Coding creativo’
Strings in Python as character sequences
Strings in Python can be seen as sequences of characters. Each character, starting from the left, is associated with an index starting from 0 and ending up to the length of the string minus 1.
Ex: sentence = ‘Coding’
Then we will have: sentence  = ‘C’; sentence  = ‘or’; sentence  = ‘d’; sentence  = ‘i’; sentence  = ‘n’; sentence  = ‘g’;
Attention, if I were to ask the program to display for example sentence , it would return me an error as the index is out of range.
Therefore the character index can assume a value ranging from 0 to len (sentence) -1. Where sentence, in this case, is the variable that contains our string.
But be careful! In the previous example, the index started from the left, but the index can also start from the right, starting from the numbers -1, -2 and so on.
In this case, therefore, the last character of our string is -1 while the first is -6.
>>>sentence = ‘Coding’
Extract sub-strings in Python
We can extract a substring from strings in Python using square brackets, where the first character of the string to be extracted is inserted and the last one separated by a colon (:).
Here is the example:
>> a = ‘Coding Creativo’
Or even more simply I can write:
These operations are called slicing which literally means “slicing”.
These are just very simple examples with strings in Python, we will come back to the topic again later.
sentence = "Coding Creativo" print(sentence[1:2]) print(sentence[:2]) print(sentence[1:]) phrase = 'Hello' phrase_2 = ' everyone.' print(phrase + phrase_2)