To assign a string to a variable, enclose the test either in apostrophes ‘…’ or in double quotes “…”:
string=’I am a cat’
string=”I am a cat”
If the string contains an apostrophe (I’m), then the entire string must be enclosed in double quotes, and vice versa. If the string contains both an apostrophe and double quotes, then a backslash \ must be used to escape the characters.
Indexing in rows
In any string, any character can be accessed using the command: string, where the number inside the square brackets indicates the position of the character. The last character of any string is denoted as string[-1]. This is called indexing.
a #this is the result
If we want to access part of the string, then we write the interval in square brackets:
- name[2:5] – from the second to the fifth characters;
- name[:5] – from the beginning of the line to the fifth character;
- name[5:] – from the fifth to the end of the line.
String concatenation (addition)
print(‘con’+’catenation’) – addition without spaces if all arguments are strings;
print(‘con’,’catenation’) – addition with spaces, not necessarily just strings;
print(‘con’+’catenation’,5) – combined addition.
print(2*(‘con’+’catenation’)) – repeat twice without spaces
An example of using string concatenation and indexing: