Python strings

/ #Python

A string can be anything from a letter, to a word or a whole sentence.

In Python you can do many really cool things with the strings. Strings in Python is actually immutable, this means that after a string has been created, you can not change it. But instead you have to create new strings, based on the original. See examples below.

Basic example

>>> s = 'Hello'
>>> print(s)
>>> print(s + 'world') # Add two strings together
>>> print(s, 'world') # Another way of adding string together. The ',' adds an additional space.
Hello world
>>> print(s + str(10)) # If you are adding a string and a int together, remember to add str() around the int
>>> print(len(s)) # Prints the length of your string

You can open up a Python interpreter and play around like this. Just open up a terminal or command line and type "python" and hit enter.

How to slice a string

Strings also come with the possibility to slice them. Here is some basic example of usage.

>>> s = 'python'
>>> s[0] # Letter number 0
>>> s[3] # Letter number 3
>>> s[3:4] # Everything between letter 3 and 4
>>> s[2:] # All after letter number 2
>>> s[:2] # All infront of letter number 2
>>> s[-1] # You can also go the other way, last character
>>> s[-2:] # Two last characters

As you can see there is a lot of ways to slice a string. If you play around, you will soon get hang of how it's working.

Other string methods

>>> s = 'Python'
>>> s.lower() # Makes whole string lowercase, you can use upper() to do the opposite.
>>> s.isalpha() # Will return true if all characters is alphanumeric.
>>> s.find('t') # Returns the index number where the string finds 't'
>>> s.startswith('P') # Returns true if the string starts with 'P'
>>> s = 'Python Programming'
>>> s.split()
['Python', 'Programming']

Now, that was a short introduction to strings. This is just a little bit of what Python strings can offer.


1) Open up a Python interpreter and create a new string with the value "Programming"
-Slice and print the string to get this result: 'ogramming'
-Slice and print the string to get this result: 'ram'

2) Almost the same as exercise 1, but here I want you to slice a string and put it together.
-Slice, put them together and print the string to get this result: 'pro ing'
-Slice, put them together and print the string to get this result: 'pro mm ing'

Feel free to add your answer here. And as always, if there is anything you are wondering about. Feel free to post your question here!


No comments yet...

Add comment


Subscribe to my weekly newsletter. One time per week I will send you a short summary of the tutorials I have posted in the past week.