Python Lesson 3: Python Strings

Advertisements

Hello everybody,

It’s Michael, and today’s lesson will be on Python Strings. I know I mentioned Strings in the previous post, but I will go into greater depth with Strings this time.

Alright, let’s open up Anacoda, launch Spyder, and start our programming!

I’m going to start with Strings. Here’s a very simple sample program:

print(‘Hello friend’)
print(“Hello friend”)

And here’s the sample output:

Hello friend
Hello friend

Notice that even though I used single quotes for the first line and double quotes for the second line, I got the same output. That’s because in Python, you can write Strings with either single or double quotes (which is not the case with Java). But keep in mind that you must always use quote pairs (a quotation mark at the beginning and end of the String)

  • You can assign strings to variables, just as you can with numbers.

However, note that multi-line strings require three sets of quotes, whether single or double. And just as with single-line strings, place the quotes at the beginning and the end of the String. Here’s a sample program with a multi-line String:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a)

And here’s the output:

The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…

Notice how the String is printed as it is displayed on the code; this is because multi-line Strings will print the code exactly as it is displayed on the compiler (which is the place where you write the code).

  • Fun fact-I got the String from Interlude, which is a track from Jay-Z’s The Black Album (2003).

Now I will show you six common methods used with Python Strings-strip(),len(), lower(), upper(), replace(), and split(). What do each of these methods do? Well, here’s a breakdown:

  • strip()-removes any white-space in the String
  • len()-returns the length of a String
  • lower()-prints the String in all lowercase
  • upper()-prints the String in all uppercase
  • replace()-replace a String with another String
  • split()-split a String into sub-strings wherever a separator is found; the separator could be something like a period or a comma.

Now let’s demonstrate each method, using the multi-line String from the previous example. Here’s a sample program with the strip() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a.strip())

And here’s the output:

The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…

Since there was no white-space in the String, the output is the same as the input. In other words, without any white-space, there’s no need to alter the String.

Now let’s try the len() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(len(a))

And here’s the output:

775

Since the len() method counts the number of characters in a String, 775 means that there are 775 characters in this String.

Now let’s try the lower() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a.lower())

And here’s the output:

the other night when i was researching what was going to be discussed today i came across a passage wrote down, i think it really exemplifies what the young brother next to me was just talking about and i learned that all things must come to an end
it is an inevitable part of the cycle of existence, all things must conclude
take the analogy of a tree that grows in brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
that came before
that came before
that came before
that came before…

Here’s the upper() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a.upper())

And here’s the output:

THE OTHER NIGHT WHEN I WAS RESEARCHING WHAT WAS GOING TO BE DISCUSSED TODAY I CAME ACROSS A PASSAGE WROTE DOWN, I THINK IT REALLY EXEMPLIFIES WHAT THE YOUNG BROTHER NEXT TO ME WAS JUST TALKING ABOUT AND I LEARNED THAT ALL THINGS MUST COME TO AN END
IT IS AN INEVITABLE PART OF THE CYCLE OF EXISTENCE, ALL THINGS MUST CONCLUDE
TAKE THE ANALOGY OF A TREE THAT GROWS IN BROOKLYN AMONG THE STEEL AND THE CONCRETE WITH ALL ITS GLORIOUS BRANCHES AND LEAVES, ONE DAY IT TOO WILL PASS ON ITS LEGACY THROUGH THE SEEDS IT DROPPED TO THE GROUND AND AS THE WIND CARRIES THESE SEEDS THROUGHOUT WHEREVER THEY MIGHT MOVE A NEW LIFE WILL BEGIN FOR EACH ONE OF THEM AS THEY STAND AS A MONUMENT TO THE ONE THAT CAME BEFORE
THAT CAME BEFORE
THAT CAME BEFORE
THAT CAME BEFORE
THAT CAME BEFORE…

Notice that the upper() and lower() methods are written as string name.upper() and string name.lower()and don’t have any parameters.

Now let’s try the replace() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a.replace(“before”, “in the end”))

And here’s the output:

The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came in the end
That came in the end
That came in the end
That came in the end
That came in the end…

The general syntax for the replace() method is string name.replace("string to be replaced", "replacement string"). Replace() will replace all instances of a certain String with another String. In the case of multi-line Strings like this one, you would replace() to replace a common word or phrase with another word or phrase. In this case, I replaced before with in the end.

And last but not least, let’s try the split() method:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a.split(“,”))

And here’s the output:

[‘The other night when I was researching what was going to be discussed today I came across a passage wrote down’, ‘ I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end\nIt is an inevitable part of the cycle of existence’, ‘ all things must conclude\nTake the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves’, ‘ one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before\nThat came before\nThat came before\nThat came before\nThat came before…’]

The general syntax of split is string name.split(separator), with the separator being the symbol where you want to split the String. In other words, I used a , as the separator, which means I wanted to split the String wherever there is a comma.

  • By the way, \n is a newline character, which is an indicator of a new line in a String.

Now, another thing I wanted to mention about Strings is that they are considered arrays, with each character in the String (including spaces) being an index in the String array. Here’s an example:

a = “””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a[100])

And here’s the output:

w

In this example, I wanted to display index 100 of the String, which would be a w. Remember that, like in Java, the first index of the array (or String-array) is 0, so index 100 would be the 101st character in the String.

  • Unlike Java, Python doesn’t have a character or char type, so a single character is a String with a length of 1.

Let’s see what happens when we select a range of indexes:

a =”””The other night when I was researching what was going to be discussed today I came across a passage wrote down, I think it really exemplifies what the young brother next to me was just talking about and I learned that all things must come to an end
It is an inevitable part of the cycle of existence, all things must conclude
Take the analogy of a tree that grows in Brooklyn among the steel and the concrete with all its glorious branches and leaves, one day it too will pass on its legacy through the seeds it dropped to the ground and as the wind carries these seeds throughout wherever they might move a new life will begin for each one of them as they stand as a monument to the one that came before
That came before
That came before
That came before
That came before…”””
print(a[400:420])

And here’s the output:

concrete with all it

In this example, I selected the 400th-420th indexes to print (which are the 401st-421st elements). I got the phrase concrete with all it as a result.

  • Always remember to use colons when selecting a range of indexes.

OK, so that’s not all I have to mention about Python Strings. There’s one more String method I want to discuss-format(). This will allow you to combine numbers and Strings in Python; you must use this method to combine numbers and Strings, as trying to use a plus sign (as you would in Java) will get you an error,

Here’s an example of how format() would be used:

a = 2019
b = “The current year is {}”
print(b.format(a))

And here’s the output:

The current year is 2019

The general syntax of the format() method is string name.format(number). The curly brackets indicate where the number would go. In this case, the number 2019 would be placed after the string The current year is to form the sentence The current year is 2019.

The format() method takes an unlimited number of arguments. Here’s an example:

a = 8
b = 11
c = 2019
d = “The current date is {}/{}/{}”
print(d.format(a,b,c))

And here’s the output:

The current date is 8/11/2019

Each of the numbers is put into their respective placeholders. By that I mean that since a is listed first, a will occupy the first placeholder. Likewise, b and c will occupy the second and third placeholders, respectively. The result will be the sentence The current date is 8/11/2019.

But what if you wanted to fill in the placeholders in a different order? Let’s say we wanted to display today’s date in British format. Here’s how you would do so:

a = 8
b = 11
c = 2019
d = “The current date is {1}/{0}/{2}”
print(d.format(a,b,c))

And here’s the output:

The current date is 11/8/2019

The print line will be the same, but this time the placeholders won’t be blank. The 0, 1, and 2 indicate which element goes in which placeholder (remember that 0 is the 1st element). In the example above, 1 (which corresponds to b) goes in the first placeholder, 0 (which corresponds to a) goes in the second placeholder, and 2 (which corresponds to c) goes in the third placeholder.

Thanks for reading,

Michael