Strings Python

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 *:

>>> phrase*4

output: HelloHelloHelloHello

In this example we have obtained a repetition of the phrase Hello, based on the numerical value specified after the operator.

Len() function

The len() function is used to find out the length of the string. Therefore:

>>> phrase = ‘Coding creativo’

>>> len(phrase)

15

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 [0] = ‘C’; sentence [1] = ‘or’; sentence [2] = ‘d’; sentence [3] = ‘i’; sentence [4] = ‘n’; sentence [5] = ‘g’;

Attention, if I were to ask the program to display for example sentence [6], 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’

>>>sentence[-1]

‘g’

>>>sentence[-6]

‘C’

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’

>>>a[0:6]

‘Coding’

>>a[7:15]

‘Creativo’

Or even more simply I can write:

>>>a[:6]

‘Coding’

>>>a[7:]

‘Creativo’

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)

Useful links

Python tutorial

Python Compiler

Install Python

Variables

Lascia un commento

Il tuo indirizzo email non sarà pubblicato. I campi obbligatori sono contrassegnati *