Strings and Sub-strings

Online Courses

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

s = "Hello World"
print(s)

Accesing array elements
You may access character elements of a string using the brackets symbol.  Computers start counting from zero, thus  s[0] is the first character:

print(s[0])

To print the second character you would write:

print(s[1])

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:

slice = s[0:5]

There you have it! String slicing is pretty easy.


Comments
Random Numbers

2 thoughts on “Strings and Sub-strings

  1. Reply
    anonymous - April 7, 2016

    “teh string”
    I laughed when I saw that XD
    So substrings are just specified like parts of a list?
    Can you do it with lists too, like
    list = [5,6,7,8,10]
    print(list[1:3])
    ?

    1. Reply
      admin - April 12, 2016

      Yes, they are specified like parts. It works with lists too. Both of them can be manipulated using the same style.

Leave a Reply

Your email address will not be published. Required fields are marked *