Strings

Strings in Python can be defined using quote symbols. An example of a string definition and output below:

This will output to the terminal:

Hello World

 
Related Course:
Complete Python Bootcamp: Go from zero to hero in Python

Accesing array elements

You may access character elements of a string using the brackets symbol,
which are [ and ]. We do so by specifying the string name and the index.  

Note: Computers start counting from zero, thus  s[0] is the first character.

 
The example below prints the first element of a string.

To print the second character you would write:

Related Course:
Complete Python Bootcamp: Go from zero to hero in Python

String Slicing

You can slice the string into smaller strings. To do so you need to specify either a starting, ending index or both. Let us illustrate that in the Python shell:

>>> s = “Hello World”
>>> s[:3]
‘Hel’
>>> s[3:]
‘lo World’
>>> s[1:3]
‘el’
>>>

If no number is given, such as in s[:3] it will simply take the beginning or end of teh string. We have accessed the string as if it was an array.

If you want to output them from your program, you have to wrap them in the print command. You can store the sliced string as a new string:

There you have it! String slicing is pretty easy.

 

Previous Post
Next Post

2 Comments

Leave a Reply