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)
s
>>> print(s + 'world') # Add two strings together
Helloworld
>>> 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
Hello10
>>> print(len(s)) # Prints the length of your string
4

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
'p'
>>> s[3] # Letter number 3
'h'
>>> s[3:4] # Everything between letter 3 and 4
'ho'
>>> s[2:] # All after letter number 2
'thon'
>>> s[:2] # All infront of letter number 2
'py'
>>> s[-1] # You can also go the other way, last character
'n'
>>> s[-2:] # Two last characters
'on'

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.
'python'
>>> s.isalpha() # Will return true if all characters is alphanumeric.
True
>>> s.find('t') # Returns the index number where the string finds 't'
2
>>> s.startswith('P') # Returns true if the string starts with 'P'
True
>>> 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.

Exercises

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!

Comments

No comments yet...

Add comment

Info

Please log in to comment!

Newsletter

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.