Python for Beginners [Strings]

Python for Beginners [Strings]

Introduction

For kicking off the first actual run in the Python for beginners series (link to the first post being here, which will guide you through the install of Python, an IDE, and some light introductory elements), we will learn about strings.

What is a string?

A string is a 'string' of text from a single letter, number/s, paragraph/s, or special character/s.

The output from this print statement is a sentence printed to the console as seen here in PyCharm:

stringExample1_pycharmOutput.png

Assigning a string to a variable

To briefly go over a variable, a variable is a name with a value attached to it. When you say the variable's name, Python says "Hey, I know that variable name! It is XYZ; let me get that for you." Let me show you an example.

NOTE: Keep in mind that you will need to avoid naming your variables that begin with functions already in Python. Here is a styling guide for you to peruse

Now we can print out those variables to see if Python remembers the values.

varExample1_pycharmOutput.png Sweet! Python remembered it, and now you can use those saved variables inside of a formatted string!

Formatting a string

Formatting strings is essential to know as you will be using it. In Python 3, there was a new implementation for formatting, usually referred to as 'f-strings'. You begin with the letter 'f', then write your string out, and when you want to call out your variable, you put the name of your variable in curly brackets. Let's take a look at its implementation.

Try that out and see what you get in your code. Ok, now we can go a little deeper with the variable. Let's say you wanted to keep a variable of the sentence pulling the initial variables 'person' and 'numbers_string'. Can we do that? Yes, yes, we can. We will need to remember that we will have to print it out if we want to see the result.

If you wonder why my string has a backslash, a carriage return, and another f"" after it, I am doing this to minimize horizontal space. When your code gets too long, you need to do this as it follows PEP-8 styling rules. This is the proper way to get that space with the carriage return and keep the formatting in your string. This will not only save your sanity but will keep other programmers from having murderous thoughts about you. You can read about it here. As previously discussed, if you are using PyCharm, it will yell at you for not following PEP-8 guidelines (Thanks, PyCharm!). If you want to read more about PEP-8, here is the link to the documentation on it. Lets check out that output. varExample2_pycharmOutput.png

Type casting

Python does an excellent job of knowing what you are doing. Let's say I wanted to assign a number to a variable. In this case, we will call the variable 'X' and give it a number of 5. We will follow it up with type() to see what type of value it is. Let's assign some of that sexy formatting we learned earlier.

If you are thinking, "Oscar, you forgot the quotes on the value for y", you would be correct and incorrect at the same time.

castExample1_pycharmOutput.png If you look at the type of X, it is 'str' and y is 'int'. Str means 'string' and int means 'integer' (I will go over Operators, ints, floats, etc. in a later tutorial). So how do we fix this? Sometimes you need to run math functions on that number, so it will need to stay a number in the variable. We can change this by something called 'casting', and here is how casting works.

By using 'str(y)' it tells Python 'Yo, I know that y is an int and all, but on this only instance, can you look at it like its a string instead?' Then Python responds, "Sure dawg." (Python is like that, super hip it says dawg a lot.) Casting can occur with floats, integers, and strings. Neat right?

Concatenate strings

Moving on to concatenation, you can take two different strings and combine them in Python, lets visit that sweet lady Karen again.

NOTE: the '\n' in this snippet introduces a new line. Put some text in a string and throw some \n's in there, try it out!

concatExample1_PyCharm_output.png

String Manipulation

The last thing we will cover is editing a string. A string is immutable, in other words, permanent.

Counting strings

Let's store the string 'Karen was a jerk-face.' in a variable called person_opinion. To count how many characters are in the string is easy. Python has a nifty built-in method called 'len()'; let's try this out.

lenExample.png There are 22 characters in the string; this is a handy little method.

Slicing strings

Python starts counting at the number 0, so if you have the text 'Karen was a jerk-face.' the 'K' would be at the place of 0, and the first 'n' would be at place 4. If you wanted to slice the string at the '-', it would be number 16. To do this, you will need to use brackets to define what you want to be cut and where.

slice_example.png In this case, it is everything before the colon that is cut. So basically, it is this '['Karen was a jerk: -face.]'. You can also do this with negative numbers by counting backward. 'print(person_opinion[:-6])' will get you the same result.

Counting words or characters in strings

If you want to count how many times that the word 'Karen' was in this string, we can use a method called 'count()'. (we can look for single characters as well)

countExample.png

Upper and lower

Changing the text to uppercase and lower case are a breeze as well using the method .upper() and .lower()

upperExample.png This is handy when comparing the text to see if it is the same as another somewhere. You would define both texts as .upper() and then compare them to see if it is True or False (which are called boolean, simple true or false).

Conclusion

Reading the documentation is always the best thing. Tutorials can always get something wrong somewhere, but documentation is gospel. Try reading Python's documentation, and work through some of these beginner string examples. The best way to learn to program is to master the fundamentals.

Have any questions?

Post them below and I will be overly happy to help!