String
String is the first object that we will focus on. An object comes from a class and is a data structure, just like variables, that can contain other variables and functions.
Methods
Some functions have been defined specifically for the object String. When a function is defined for an object, we call it a method of this object. To use a method on a object, the syntax is object.method()
.
There are multiple predefined methods that we can use on a String:
>>> text = "STOP YELLING !"
>>> newText = text.lower()
>>> newText
'stop yelling !'
>>> newText = text.capitalize()
>>> newText
'Stop yelling !'
>>> newText = text.upper()
>>> newText
'STOP YELLING !'
>>>
Concatenate
The +
sign allows you to concatenate two strings:
>>> name = "Marc"
>>> message = "Hello"
>>> welcome = message + name
>>> welcome
'HelloMarc'
>>> welcome = message + " " + name
>>> welcome
'Hello Marc'
>>> age = 21
>>> welcome = message + " " + name + " you are " + str(21)
>>> welcome
'Hello Marc you are 21'
>>>
Length
To get the length of a String (the number of characters that it contains), we use the function len:
Select
A String is composed by multiple characters. You can easily select each of those characters individually thanks to their index. You just need to specify the index of the character you want between []
.
You can also select part of a string by specifying the start index and the end index between []
and seperated by :
.
>>> text = "Hello students"
>>> text[0] #First character
'H'
>>> text[2] #Third character
'l'
>>> text[-1] #Last character
's'
>>>
>>> text = "hello, how are you?"
>>> text[7:10]
'how'
>>> text[11:14]
'are'
>>> text[:5]
'hello'
>>> text[7:]
'how are you?'
>>>
Summary
- A String is an object and you can use functions specifically designed for it, called methods. The syntax is:
object.method()
. - The
+
sign allows you to concatenate two Strings - The
len()
function returns how many characters there are in your String. - You can directly access a character from a String using the index method:
text[position_in_the_string]
-
It is possible to select part of a String by writing:
my_text[start_index:end_index]
- The
end_index
is not included in the selection. - If you donβt specify the
start_index
, Python will assume that it is 0. - If you donβt specify the
end_index
, Python will assume that it is the last index of the String.
- The