Learning Python - step by step - 3 - strings

/ #Python


In the previous post we learned the basics about string. In this part, we'll learn how to create a python file and execute it in the command line.

Creating the first file

Open up your favorite text editor or something as simple as Notepad. We can begin with something really simple. Write the following code and save the file as python1.py.

name = 'Stein Ove'
print(name)

The code should look familiar if you followed the previous part of this tutorial series. Open up your command line and go to the directory you saved python1.py in.

When you're ready, type the following command:

$ python python1.py

When you run this command, you tell "python" to execute the file (python1.py) you just created. "Stein Ove" should be printed on the next line in your command line.

More about strings

We know a little bit about strings and we know how to execute a python script with the command line. Strings comes with a lot of different handy functions.

What if we want to make all the letters lowercase or maybe uppercase? Let's try to do that:

name = 'Stein Ove'
name_lower = name.lower()
name_upper = name.upper()

print('Name lower:', name_lower)
print('Name upper:', name_upper)

If you run this script, you should see something like this:

Name lower: stein one
Name lower: STEIN OVE

Isn't this really cool? You're just adding a function after a variable and you're able to manipulate how a string is presented on the screen.

Another example we can try is to check if the name contains a letter or a word:

name = 'Stein Ove'
print(name.find('Stein'))
print(name.find('Ove'))
print(name.find('Python'))

If you run this, the first line will say 0 and the second line will say 4. "Stein" is found at index position 0 of the string (name) and "Ovf" is found at index position 4.

The last line will say -1, because "Python" can't be found inside the string.

Summary

In this part, you have learned more about strings. But there's still a lot more you can do with strings, but we don't want to be overwhelmed, so we'll go over more string functions in later parts of this tutorial series.

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.