© The Author(s), under exclusive license to APress Media, LLC, part of Springer Nature 2021
A. ElumalaiIntroduction to Python for Kids https://doi.org/10.1007/978-1-4842-6812-4_8

8. Play with Letters and Words

Aarthi Elumalai1  
(1)
Chennai, Tamil Nadu, India
 

In the previous chapters, we took a break from learning Python basics and we learned all about Turtle and using it to draw straight lines, shapes that are formed with straight lines, circles, curves, and even text. We finished the chapter with a bunch of cool and colorful mini projects.

In this chapter, we’ll go back to the basics of Python and learn about strings, what they are, how to create them, how to manipulate them using various pre-defined functions available in Python, and getting direct inputs from the users of your programs to make your projects more dynamic. As usual, we’ll finish the chapter with some mini projects, but we’ll use Turtle to make our projects colorful now.

What are strings?

Strings…strings…strings. Such a grown-up word for something so simple. Strings are just letters and number, strung together. Sentences, phrases, and words – they are all strings. Single letters can also be strings.

../images/505805_1_En_8_Chapter/505805_1_En_8_Figa_HTML.jpg

Do you remember the print statement? When we first started using the print() function, we wrote something within quotes inside the bracket. Was it ‘Hello there!’? Yes indeed.

That was a string. Print statements usually have strings inside of them. But that’s not where it ends. You can store strings in variables as well, just like you do with your numbers.

Now that you know what strings are, let’s learn how to create them next! This is going to be a longer than average chapter, so buckle up! I promise all the exercises and fun projects will make up for the length. ../images/505805_1_En_8_Chapter/505805_1_En_8_Figc_HTML.gif

Let’s create some strings

I’m going to create a new script file called strings.py and use it for this chapter.
a = 'This is a string'
The variable “a” now has the string ‘This is a string’. You can place the string within double quotes as well.
a = "This is a string"
Let’s try printing this string now, shall we? It’s quite simple. You use the print statement again, but instead of typing the string within quotes inside the brackets, you just type the name of the variable that contains the string, without quotes, like this:
print(a)
Now, if you run the preceding code, you’ll get this:
RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
This is a string

We successfully printed our string. Yay!

Your strings can have numbers as well, and they’d still be considered a string. Anything within quotes is a string. Let me place a number within quotes and check its type by using the type() method.
a = "1234"
print(type(a))
When you run the preceding code, you’ll get this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
<class 'str'>

Look at that! Even though “a” has a number, 1234, since it was placed inside quotes, Python automatically considered it a string.

I want lines and lines of strings!

All’s well and good with strings as long as you stick to creating single-line strings. What if we need multiple lines? We can’t keep creating a separate print statement for each new string line. That’s what we did in our very first mini project, where we printed out Susan Smith’s introduction, remember? That was very inconvenient!

Why don’t we try creating multiple lines inside of string format and see what happens?
a = "This is the first line.
This is the second line.
This is the last line."
In the preceding example, “a” has three string lines, wrapped inside double quotes. Let’s run it and see what happens (Figure 8-1).
../images/505805_1_En_8_Chapter/505805_1_En_8_Fig1_HTML.jpg
Figure 8-1

Multi-line string with double quotes – error

Uh oh. I can’t even run the code. I immediately get a popup with the preceding error. What we wrote previously is not acceptable code at all. So, how can we create multiple lines of string? Do you remember multi-line comments in Chapter 3? We used three single quotes, without space before the comment, and the same, after the comment, and that created a multi-line comment.

I have a confession to make. That syntax is actually the syntax of a multi-line string. We just borrowed it to create a multi-line comment because a multi-line string that hasn’t been stored in a variable and just stands as it is would be ignored by Python, so it technically acts a comment (though it is not).

Alright, enough chit chat. Let’s create a multi-line string now. I’m going to replicate Susan Smith’s introduction, but I’m going to use multi-line strings to create and print it.
intro ='''Hello there!
My name is Susan Smith.
I am 9 years old.
I love puppies!'''
print(intro)
When I run the preceding code, I get this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
Hello there!
My name is Susan Smith.
I am 9 years old.
I love puppies!

Simple and neat, don’t you think? ../images/505805_1_En_8_Chapter/505805_1_En_8_Figd_HTML.gif Yes!

My string has quotes! :O

Oh my, our string has quotes, and we’re getting an error!
intro =""Hello!", said Susan"
I got this (Figure 8-2).
../images/505805_1_En_8_Chapter/505805_1_En_8_Fig2_HTML.jpg
Figure 8-2

Single and double quotes in the same string – error

Bummer. ☹

Well, I could change the quote that wraps around the string.
intro ='"Hello!", said Susan'
print(intro)
Does it work?
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
"Hello!", said Susan

Yes! ../images/505805_1_En_8_Chapter/505805_1_En_8_Fige_HTML.gif

But what if my string has both single and double quotes? Maybe a string like the following one:

“That’s my Teddy”, said Susan.

I can’t just interchange double quotes for single quotes in the preceding string. I need a way to tell Python that the single quote in “That’s” is actually a part of the string and not a part of the code. We have something called an escape character in Python, which is just a backslash, “”. You can use that before the quote that’s part of a string (either a single or double quote), and Python will ignore it while running your code.

Let’s try.
intro = '"That's my Teddy", said Susan.'
print(intro)
Run the preceding code, and we’ll get this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
"That's my Teddy", said Susan.

Yes, it works!

Let’s join two or more strings

When we used the “+” symbol with two or more numbers, they were added together. Would you like to see what would happen if you do the same with strings? Okay!

I’ve created two variables str1 and str2 which hold the strings ‘Hello’ and ‘there!’. I’ve created a third variable “string” and assigned the addition of str1 and str2 to it.
str1 = 'Hello'
str2 = 'there!'
string = str1 + str2
print(string)
Let’s print string and see what we get:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
Hellothere!

Oh, look at that. It just put the string inside str1 after the string inside str2. That’s interesting. Addition didn’t take place, even though we used the addition operator.

In fact, there is a name for this string operation. It’s called string concatenation . When you use “+” on two or more strings, you add them together, yes, but not in the traditional sense. You just merge them together, in the order they are added in.

Something’s bothering me about my result though. “Hellothere!” isn’t what I wanted. I wanted a space between those words. That’s proper usage of that phrase. So, why don’t I just add that?
str1 = 'Hello'
str2 = 'there!'
string = str1 + " " + str2
print(string)
That was simple! We just created another string that had just one space in it and added it before str2. Let’s run the preceding code, and we’ll get this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
Hello there!

Now, that looks right. So, as you can see, you can concatenate more than two strings, and they can either be inside variables or as is (within quotes). Even a space is a string, if placed inside quotes.

Concatenation in print()

You can apply string concatenation in print() as well.
a = 'Hi!'
print('Susan says, "' + a + '"')

Does it look a bit complicated? Not to worry. I’ve wrapped the first part of the string, “Susan says”, with a comma, a space, and a double quote at the end in single quotes. The next part of the string is whatever is inside the variable “a”, so I concatenated the two strings. The final part of the string is the closing double quote which is also wrapped inside a single quote. Alternatively, I could have just used double quotes throughout and used the escape character to distinguish the string’s double quotes.

If I run the preceding code, I’ll get this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
Susan says, "Hi!"

Nicely done!

Empty string

All these string operations reminded me of something! There’s something called an empty string , where you just don’t type anything between the quotes, not even an empty space.
a = ''

In the preceding example, the variable “a” is storing an empty string. If you print that out, you’d get nothing in the output (not even a space). Try and see! ../images/505805_1_En_8_Chapter/505805_1_En_8_Figf_HTML.gif

Accessing characters in strings

I want to introduce you to a mind-blowing topic in strings! You can actually access, retrieve, and even modify specific characters (letters) in strings. How cool is that? You can make changes to the string on a character level with this feature.
a = 'Hello there!'
Look at the following string index chart. Every character in a string has an index. In fact, they have two indices, a positive index and an equivalent negative index. You can access those characters by using those indices.
../images/505805_1_En_8_Chapter/505805_1_En_8_Fig3_HTML.jpg
Figure 8-3

String index chart

As you can see in Figure 8-3, the positive indices start from 0 and increase in value toward the left. The negative indices start from the last position at –1. The space has an index, and so does the exclamation point. It isn’t just for the letters/numbers.

Okay, that’s all well and good, but how do we access these indices? Simple! Type the name of the string and open and close square brackets, and type in the relevant index within the brackets, and you’re good to go.

As you can see, the indices start from 0, and the last one is the length of the string subtracted by 1. Spaces in a string also take up indices.

So, if I want to retrieve the first character of the string, “H”, this is what I’d do:
print(a[0])
When you run the preceding code, you’d see this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
H

Perfect!

Now, if I were to retrieve the last character of the string, I’d first calculate the length of the string. The length is 12 in this case, including the space. Now let’s subtract it by 1, as follows:
print(a[12-1])
When you run the program, your interpreter (IDLE) will automatically do the calculation to arrive at 11 for the index. The result is this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
!

Yup, that’s right.

Negative indices

As you saw in the preceding image, you have both positive and negative indices for the same characters in a string. Let’s try to access “o”, which is in the positive index 4 (fifth position on the string) and –8 in the negative index position.
print(a[-8])
Run the preceding code, and you’ll get this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
O

It works perfectly!

So, the first character would be at a[–12], and the last character would be at a[–1].

Slicing a part of a string

You can extract a part of a string and not just a single character with your indices. That’s called slicing.

Slicing follows the same pattern as character extraction, but the only difference is you’ll have to give a range within the square brackets. If I want to extract the first four characters in a string, I’ll give the range as 0:4 because the first character’s index is 0 and the fourth character’s index is 3. In slicing, the end of the range (4 in our case) would be omitted. Hence, 0:4 and not 0:3. Let’s try and see what we get!
a = 'Hello there!'
print(a[0:4])
Run the preceding code, and you’ll get this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
Hell

Yup, we got it!

What if we want the last four characters instead? You can do it in two ways. The positive index of the last character is 11, and that of the fourth last character is 8, so we can do the following:
print(a[8:12])
Run the preceding code, and we’ll get this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
ere!
Great! So far so good. But what about negative indices? The negative index of the last character is –1 and that of the fourth last character is –4, so we can do the following instead:
print(a[-4:-1])

Notice how we’ve given –4 (fourth last character) first, which will be included. But –1 would not be included, am I right? That’s how the syntax works, and that’s the last index.

Okay, let’s run the preceding code and see if it works:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
Ere

Ah well, it doesn’t work. We’re missing a “!”. ☹

What can we do? Well, in situations like this, where you start from a point and need the rest of the string (fourth last position to the end of the string), you can just leave the last number in the range blank, like this:
print(a[-4:])
Run the preceding code, and you’ll get this:
= RESTART: C:/Users/aarthi/AppData/Local/Programs/Python/Python38-32/strings.py
ere!

Perfect!

String methods – magic with strings!

Just like with numbers (Chapter 5), you have plenty of pre-defined methods that’ll help you play with numbers. Some of them look magical! You’ll see.

There’s a complete list of Python string methods and explanation of what they do in the Python official docs. Here’s the link: https://docs.python.org/2.5/lib/string-methods.html.

You can refer to the preceding doc in the future. I’ll try to cover most of the important methods, though I can’t cover every single one as that would just make the chapter too long. Don’t worry though. Once you learn a few, you’ll be able to decipher how the rest work.

Alright, let’s get started!

Why don’t we start with something simple? The len() method is used to find the length of the string.

The syntax of the method is as follows: len(string)
a = 'Hello there!'
print(len(a))
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
12

Count the number of characters in the string (including the space) and you’ll notice that its length is indeed 12.

Capital and small

Alright, now let’s look at the other methods. The “capitalize()” method capitalizes the first word in the string. It doesn’t change the original string. It just creates a copy that you can either assign to a new variable or print.

The syntax is like this: string.capitalize().

The “string” could either be the exact string inside quotes or the variable that’s storing the string.
a = 'i am here'
print(a.capitalize())
print(a)
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
I am here
i am here

See, the capitalization did not affect the original string.

In the same vein, you can capitalize all the characters (alphabets) of a string using the upper() method. This creates a copy too. All the string methods create copies. They rarely make changes to the original string.
a = 'i am here'
print(a.upper())
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
I AM HERE
Similarly, you can change all the capitalized letters to small letters in a string using the lower() method.
a = 'I AM here'
print(a.lower())
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
i am here

Did you notice how some of the letters were already small? Those just go unchanged with this method.

Instead of just capitalizing the first letter of the entire string, like in capitalize, you can actually capitalize every first letter of every word in the string using the title() method.
 a = 'i love chimpanzies!'
print(a.title())
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
I Love Chimpanzies!

Misc methods

Using the count method, you can return the number of times a word or letter or phrase appears in a string.

The syntax is string.count('word').

This method is case sensitive, just like the rest of the methods in Python, so if you want “word”, don’t type it as “Word”.

To test this method, I’m creating a multi-line string like how I taught you:
a = '''Susan is a lovely girl.
Barky is Susan's best friend.
Barky plays with Susan'''
Let’s count how many times ‘Susan’ and ‘Barky’ are mentioned in the preceding string, shall we?
print(a.count('Susan'))
print(a.count('Barky'))
The result is this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
3
2

Whoo! ../images/505805_1_En_8_Chapter/505805_1_En_8_Figg_HTML.gif

You can trim extra spaces in a string with the strip() method.
a = '         Hello there!          '
print(a.strip())
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
Hello there!

No spaces at all!

There are left and ride side versions of the same method. The rstrip() method only strips the whitespaces in the right side of the string. The lstrip() method does the same for the left side of the string. Why don’t you try them out and see if they work right?

Remember that big string we just worked with? What if we made a mistake? What if we were going to talk about Ronny and not Susan? We need to swap their names, am I right? You can use the replace method to do that. The syntax is string.replace('original','replaced').
a = '''Susan is a lovely girl.
Barky is Susan's best friend.
Barky plays with Susan'''
print(a.replace('Susan','Ronny'))
Let’s run the preceding code, and we’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
Ronny is a lovely girl.
Barky is Ronny's best friend.
Barky plays with Ronny

See, it’s Ronny now!

We can also find the positions from which a particular word or letter or phrase starts in a string. Remember, string positions start from 0, so you’ll always be one count behind.
a = "I love coding. I have fun with coding"
print(a.find('coding'))
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
7

Count the characters, including the spaces, and you’ll notice that the first occurrence of “coding” starts at the position 8 (and hence 7 with respect to Python strings).

What if the phrase isn’t found?
print(a.find('Coding'))
You know that “coding” is different from “Coding” in Python, so it wouldn’t be found in the string.
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
-1

Oops, the result was a –1.

The index() method does exactly what the find() method does. The only difference is that it returns an error if the phrase is not found, and not –1. Why don’t you try to do the same with index()?

With the split method, you can literally split a string into a list. We’ll be looking at what lists are in a future lesson. For now, just know that lists hold multiple values within them, separated by commas.

In order to use the split method, you need to give a separator. Let’s say I want the string to be taken apart by word. Then I’d give a single space as the separator.
a = "I love coding."
print(a.split(' '))
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
['I', 'love', 'coding.']

That’s a list and it holds our string, separated by word.

True? False?

Before I move further with the methods, I want to teach you the concept of true and false in Python, or any programming language, really. It’s quite simple. If something is true, then your program will return “True”. If a condition is false, then you’ll get “False”. That’s it.

For example, let’s say I want to see if my string has the words “best friend” in it. I really want to know if Barky is Ronny’s best friend or not.

I’ll have to use the “in” keyword. Keywords are special words that do something in Python. The “in” keyword checks whether what the word or phrase we want looked up is inside our string or not.
string = "Barky is Ronny's best friend."
print('best friend' in string)
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
True

But as you know, Python is case sensitive. So, “best friend” is not the same as “Best friend” or any other versions. So use the words as is, okay?

Let’s look at another example, shall we?
print('Python' in 'Python is fun')

When you run the preceding code, you’ll get True.

But if you ask for this:
print('Coding' in 'Python is fun')

you’ll get False because ‘Coding’ isn’t in the string ‘Python is fun’.

Similarly, you can test for a lot of other strings in your string.

Would you like to see if your string has both letters and numbers? Use the isalnum() method. It returns true only if every word in the string has both letters and numbers, like this:
a = 'number123 number253'
print(a.isalnum())
The preceding code will return True, while the below code:
a = 'This is a number: 123'
print(a.isalnum())

will return False, because most of the words have just letters and not letters and numbers.

The isalpha() method returns true if every single character in the string is an alphabet (no number or special characters at all). The isnumeric() method returns true if every single character in the string is a number (no alphabet or special characters).

Islower() returns true if all the characters are small. Isupper() returns true if every character is capitalized.

I want you to use these methods while giving different possibilities and explore how they truly work. Deal?

You can refer to the link I gave in the “String methods – magic with strings!” section to get the rest of the methods and use them in your experiments too. Have fun! :P

Hey, I know what you’re thinking.

“Oh man, that’s a lot of methods. How would I ever remember them all?”

Well, why should you? I’ll let you in on a biggg secret…Shhhhhh

Programmers don’t try to memorize syntaxes when they start out. That’s what Google’s for. They just create a lot. They solve a lot of puzzles, create fun projects, and Google for syntaxes when they get stuck. Over time, the syntaxes just get stuck in their head because they’ve used them so much.

So, forget about memorizing. Use this book as a reference. Solve the puzzles, create the mini projects with your twist, and take the big projects to the next level, and by the time you’re done with them all, you’ll be a master of Python. Just have fun. ../images/505805_1_En_8_Chapter/505805_1_En_8_Figh_HTML.gif

String formatting

The print statement is boring and limiting. ☹ You can’t format it the way you want, and if you try, you’ll drown in a mess of quotes. But more than that, you can’t print numbers (even if they’re in variables) with strings! :O

Let me prove that to you.
a = 4
b = 5
sum = a + b

So now, I want to print the following statement: 4 + 5 = 9, and I want to print it using the variable names and not the actual values, to keep things dynamic. I can maybe change the value of a variable, and my print statement will automatically change too.

We should be able to do that with the concatenation we learned about before, right? Let’s try.
print('The answer is: ' + a + ' + ' + b + ' = ' + sum)

The preceding code should ideally result in this:

The answer is: 4 + 5 = 9

But this is what we get:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
Traceback (most recent call last):
  File "C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py", line 4, in <module>
    print('The answer is: ' + a + ' + ' + b + ' = ' + sum)
TypeError: can only concatenate str (not "int") to str

Essentially, what the error says is you can only concatenate a string (anything within quotes) with a string, and the variables that contain numbers (without quotes) within them are not strings.

Not only was that statement very hard and confusing for me to create, it simply didn’t work.

That’s where formatting comes in. You can format the way your print statements are written. Just place {} (without space) where your variables come in, and you can fill them later using the format method.

Let’s start with something simple.
a = 'apple'

Let’s say I want to print ‘This is an apple’, where the value ‘apple’ comes from the variable a.

I’d type the entire string out, but place {} in the place of ‘apple’, like this:
'This is an {}'
Next, I’ll tag the format method and place the variable “a” inside the parenthesis. Python will automatically replace the {} with the value inside your variable.
a = 'apple'
print('This is an {}'.format(a))
When you run the preceding code, you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
This is an apple

Very simple, wasn’t it? You don’t have to mess around with spaces and quotes anymore, whoohoo!

Let’s go for a more complex example now, shall we?
a = 'Apples'
b = 'Bananas'
If I wanted to print “Apples and Bananas are good for your health”, this is how I’d do it:
print('{} and {} are good for your health'.format(a,b))
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
Apples and Bananas are good for your health

Did you notice how I have the variables inside the format, separated by commas?

You can place the first part of the string inside a variable and use that as well, like this:
a = 'Apples'
b = 'Bananas'
s = '{} and {} are good for your health'
print(s.format(a,b))
Or, if I want Bananas to be printed first and then Apples, but I don’t want to change the order in which they are listed, I can just label them in the string to be printed, like this:
s = '{1} and {0} are good for your health'
print(s.format(a,b))

Indices start with 0 in Python, remember?

Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
Bananas and Apples are good for your health
Alright. Now that we’re experts at using format() to design our print, why don’t we go back to our original problem?
a = 4
b = 5
sum = a + b
Let’s format our string!
print('The answer is: {} + {} = {}'.format(a,b,sum))
Run the preceding code, and you’ll get this:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
The answer is: 4 + 5 = 9

YES! Easy and neat, just the way it should be. ../images/505805_1_En_8_Chapter/505805_1_En_8_Figi_HTML.gif

Getting input from the users (start automation)

So far, we’ve just been fixing the values of our variables. That’s so boring! I want automation. That’s what programming is all about, isn’t it?

I want to give a different number every time I run my addition program, a different string every time I want to print a message. That’s what an input is. A user or the person who runs the program gives values that can be used in the program to get a result. Those values are called inputs.

In Python, you can use the input() method to get inputs. Pretty straightforward, isn’t it?

When you run a program, it’ll ask you for the value, and wait until you give the same. That is called prompting.

I’m going to start simple. I’m going to get a message I can immediately print. It’s always good practice to include a message while asking for inputs, so the user know what value they’re expected to give. You can include the message within quotes inside input’s parenthesis.
message = input('Enter your message: ')
print('Here is your message: ' + message)

I’ve prompted the user to enter a message, and I’ve received the same inside the variable “message”. Then I’ve printed it out. Simple.

When I run the preceding code, this is what I’d get first:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
Enter your message:

The program has stopped at this stage because it’s waiting for my message.

Let me enter it now:
Enter your message: I love Python!
When I press Enter, I’ll get this:
Here is your message: I love Python!

It works perfectly! My message was printed out in the format I wanted.

String to int or float conversion

We looked at inputs and how we can dynamically get values and use them in our program. Isn’t calculation one of the best ways to use dynamic values? I want a different number every time I perform an addition operation.

Let me use input for the same and see if it works.
a = input('First number: ')
b = input('Second number: ')
sum = a + b
print('{} + {} = {}'.format(a,b,sum))

Everything looks good in the preceding code snippet. It should work, right? Wrong.

When I run it, this is what I get:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
First number: 5
Second number: 2
 5 +  2 =  5 2

My program prompted me for the two numbers, and I entered them. All good till now. But then, things went wonky with the addition.

Why?

You haven’t entered numbers at all. When you give values to an input, your program considers it as a string, not a number. So, what happened here is string concatenation, and not addition.

How do we make Python look at our inputs as numbers? You need to convert them, of course! Remember how we converted different types of numbers? Similarly, you can convert a string to either an integer using the int() method or a floating-point number using the float() method.

Let’s modify our code:
a = input('First number: ')
#Convert 'a' into an integer and store it back in 'a'
a = int(a)
b = input('Second number: ')
#Convert 'b' into an integer and store it back in 'b'
b = int(b)
sum = a + b
print('{} + {} = {}'.format(a,b,sum))
The only thing I changed in the code is the integer conversions after getting each input. I’ve stored the converted values back in the same variable as well. Let’s run this code and see if it works:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
First number: 5
Second number: 2
5 + 2 = 7

Phew! It works now.

Mini project – take Turtle text to the next level!

This is going to be a simple project. We’re going to take your user’s name as input in real time and print it out, in big, colored font in our Turtle screen:
  1. 1.
    Let’s set up our Turtle first:
    import turtle
    s = turtle.getscreen()
    t = turtle.Turtle()
     
  2. 2.

    Next, let’s get create a variable name that gets the user’s name as input:

     
name = input("What's your name? ")
  1. 3.

    We won’t have to convert this string in any way, since we’re just going to concatenate it with another string. Let’s create our customized greeting on Turtle now. Before we do that, let’s create the exact string we want to print and assign it to a variable “greeting”.

     
greeting = 'Hi {}!'.format(name)
  1. 4.
    Now, let’s set a pen color of, maybe, Dark Violet? And let’s also move the pen to the position –250,0 so it draws in the center of the screen.
    t.pencolor('DarkViolet')
    t.penup()
    t.goto(-250,0)
    t.pendown()
     
  2. 5.
    Finally, let’s create our text.
    t.write(greeting,font=('Georgia',45,'normal','bold','italic'))

    I’ve placed the variable “greeting” with the text we need in place of the actual text, and I’ve also set the font style as ‘Georgia’ and size as 45, and I’ve made the text bold and italic. I’ve omitted the move property, so it’s going to be “false” by default (no arrow below the text).

     
  3. 6.
    Finally, let’s hide our turtles:
    t.hideturtle()
    turtle.hideturtle()
     
Let’s run this program now:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
What's your name? Susan Smith
It asked for the name. I gave the name as “Susan Smith”, pressed enter, and voila! (Figure 8-4).
../images/505805_1_En_8_Chapter/505805_1_En_8_Fig4_HTML.jpg
Figure 8-4

Colorful greeting

We have our greeting, and it looks pretty too! ../images/505805_1_En_8_Chapter/505805_1_En_8_Figj_HTML.gif

Mini project – shout at the screen

We’re going to do what the title says. Let’s shout at the screen, shall we? Oh wait…or is the screen going to shout at us? Either way, let’s do some shouting! Whoo!

../images/505805_1_En_8_Chapter/505805_1_En_8_Figb_HTML.jpg

The concept is simple. We’re going to get a string input from the user. The message is going to be “Enter what’s on your mind in less than 3 words”. Less than three words so our text can be displayed in a big enough font in one line. In the later chapters, you’ll learn the tools needed to get as many words of input as you want, and make sure you print them all by making space, so don’t worry about that right now.

Then, we’re going to capitalize the result, add two or more exclamation points at the end, and print everything in Turtle. Simple, right? Let’s do it!
  1. 1.
    To start, let’s set up the Turtle package:
    import turtle
    s = turtle.getscreen()
    t = turtle.Turtle()
     
  2. 2.
    Then, let’s get the input:
    message = input("Enter what's on your mind in 3 words or less: ")
     
  3. 3.

    Finally, let’s format the message we want to shout! Our “message” is probably in small letters. How do we convert every single letter in our message to uppercase? Yes! The upper() method. Let’s use that, and tag on three exclamation points at the end, to make our message more dramatic!

     
shout = '{}!!!'.format(message.upper())
  1. 4.
    Now, I’m going to move the pen to –250,0 and change the color of the pen to Red, because nothing says shouting more than Red. ../images/505805_1_En_8_Chapter/505805_1_En_8_Figk_HTML.gif
    t.pencolor('Red')
    t.penup()
    t.goto(-250,0)
    t.pendown()
     
  2. 5.

    Now, on to the main part of the program. Let’s create our Turtle text. I’m going to use the ‘Arial Black’ font for this. The size of the font is going to be 45, but I’m going to stop at making the text bold. No italics this time.

     
t.write(shout,font=('Arial Black',45,'normal','bold'))
  1. 6.
    Finally, let’s hide the turtles.
    t.hideturtle()
    turtle.hideturtle()
     
Let’s run everything. My message is going to be “what is this?”. Let’s see what we get:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py

Enter what’s on your mind in three words or less: What is this?

When I press Enter and look at my Turtle screen, I get this (Figure 8-5).
../images/505805_1_En_8_Chapter/505805_1_En_8_Fig5_HTML.jpg
Figure 8-5

Shout at the screen

Yes! Success!

Mini project – reverse your name

I’m going to teach you something fun while solving this project. So far, we’ve seen all kinds of ways in which we can manipulate our strings. Why don’t we look at one more before we end this chapter?

Did you know that you can reverse your string? Yes, that’s right! Complete reversal, with just one teeny tiny line of code. Would you like to try?

Let’s create a program that gets the name of the user as input, reverses their name, and displays it in the Turtle screen:
  1. 1.
    Let’s set up Turtle, as usual.
    import turtle
    s = turtle.getscreen()
    t = turtle.Turtle()
     
  2. 2.

    And get the user’s name and place it in the variable “name”.

     
name = input("What's your name?")
  1. 3.

    Now comes the interesting part! We’re going to format the string we want displayed as usual. We’ve created a variable “reverse” to store the string. But how do we reverse? Remember how we used to use square brackets to access separate characters, extract parts of the string, and so on? Also, do you remember negative indices? There you go!

    If you use the following syntax, you can reverse your string: string[::–1]. So, that’s a double colon, followed by a –1. Simple as that! ../images/505805_1_En_8_Chapter/505805_1_En_8_Figl_HTML.gif

     
reverse = '{}'.format(name[::-1])
  1. 4.
    Finally, let’s change the color of the pen to ‘Gold’, shift position to –250,0, and draw the reversed string on screen.
    t.pencolor('Gold')
    t.penup()
    t.goto(-250,0)
    t.pendown()
    t.write(reverse,font=('Georgia',45,'normal','bold'))
    t.hideturtle()
    turtle.hideturtle()
     
Let’s run the program:
= RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
What's your name? Susan Smith
Now, click Enter, and you’ll get this (Figure 8-6).
../images/505805_1_En_8_Chapter/505805_1_En_8_Fig6_HTML.jpg
Figure 8-6

Reverse your name

Hehe, her name was reversed, alright. :P

Mini project – colorful and dynamic Math

In the numbers chapter, we had to resort to doing boring calculations with pre-defined numbers and no colors! ☹

So, I thought we could have some real fun with numbers before we move on to the next chapter. Shall we?

In this project, we’re going to perform addition, multiplication, subtraction, and division on two given numbers. Boring, I know! But this time around, we’re going to get the two numbers as dynamic input from the user and display the results, in color, in Turtle. Interesting? I know!
  1. 1.
    Let’s set up Turtle first.
    import turtle
    s = turtle.getscreen()
    t = turtle.Turtle()
     
  2. 2.
    Then, let’s get the inputs for the first and second numbers we’re going to use in our operations. But there’s an issue! We can’t use them as it is. They are in string formats, remember? So, let’s convert them to integers and assign them back to the same variables.
    num1 = input("Enter the first number: ")
    num1 = int(num1)
    num2 = input("Enter the second number: ")
    num2 = int(num2)
     
  3. 3.
    Now, let’s do the addition. We’re going to create a variable called display which is going to hold all the formatted strings of the four operations.
    #Addition
    add = num1 + num2
    display = "{} + {} = {}".format(num1,num2,add)
     
  4. 4.
    Once formatted, let’s position our pen at –150,150 so our drawing is aligned to the middle of the screen. Then, let’s change the color of the pen to “Red” and draw the text.
    t.penup()
    t.goto(-150,150)
    t.pendown()
    t.pencolor("Red")
    t.write(display,font=("Georgia",40,"normal","bold"))
     
  5. 5.
    Do the same for subtraction now, except that the position is going to be –150,50 now and the color is going to be “Blue”.
    #Subtraction
    sub = num1 - num2
    display = "{} - {} = {}".format(num1,num2,add)
    t.penup()
    t.goto(-150,50)
    t.pendown()
    t.pencolor("Blue")
    t.write(display,font=("Georgia",40,"normal","bold"))
     
  6. 6.
    For multiplication, the position is going to be –150,–50 and the color is going to be “Green”.
    #Multiplication
    mul = num1 * num2
    display = "{} * {} = {}".format(num1,num2,add)
    t.penup()
    t.goto(-150,-50)
    t.pendown()
    t.pencolor("Green")
    t.write(display,font=("Georgia",40,"normal","bold"))
     
  7. 7.
    For division, the position is going to be –150,–150 and the color is going to be “Violet”.
    #Division
    div = num1 / num2
    display = "{} / {} = {}".format(num1,num2,add)
    t.penup()
    t.goto(-150,-150)
    t.pendown()
    t.pencolor("Violet")
    t.write(display,font=("Georgia",40,"normal","bold"))
     
  8. 8.
    Finally, let’s hide the turtles.
    t.hideturtle()
    turtle.hideturtle()
     
  9. 9.
    Now, let’s run the program. It asks for inputs first. Our inputs are going to be 10 and 5.
    = RESTART: C:UsersaarthiAppDataLocalProgramsPythonPython38-32strings.py
    Enter the first number: 10
    Enter the second number: 5
     
When we click Enter, this is what we get (Figure 8-7).
../images/505805_1_En_8_Chapter/505805_1_En_8_Fig7_HTML.jpg
Figure 8-7

Colorful and dynamic Math

Beautiful! ../images/505805_1_En_8_Chapter/505805_1_En_8_Figm_HTML.gif

Summary

In this chapter, we looked at strings, what they are, creating single-line, multi-line, and empty strings, creating strings with quotes, concatenating two or more strings, accessing characters in strings, extracting parts of a string, string slicing, how to manipulate strings in different ways, and getting inputs from users and using them in our program.

In the next chapter, let’s look at how we can command our program to do whatever we want. We’re going to look at “if” statements, creating multiple options with “if else” and “if elif else” statements, and a lot more. It’s going to be fun! ../images/505805_1_En_8_Chapter/505805_1_En_8_Fign_HTML.gif

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset
3.138.102.178