Python: Strings, Numbers and Comments

Aldrin Caalim
Probably Programming
7 min readDec 13, 2020
Photo by Emily Morter on Unsplash

This is a summary of Chapter 2 of “Python Crash Course: A Hands-On, Project Based Introduction to Programming” by Eric Matthes

Strings

In Python, a string is a series of characters inside quotes. You can use single or double quotes around your strings like this:

double_quotes = "This is a string with double quotes."
single_quotes = 'This is a string with single quotes.'
print(double_quotes)
print(single_quotes)
>>> This is a string with double quotes.>>> This is a string with single quotes.

The flexibility to use single or double quotes allows us to use quotes and apostrophes within strings:

as_quote = 'And then I told them, "Now is not the time!"'
as_apostrophe = "It isn't so."
print(as_quote)
print(as_apostrophe)
>>> And then I told them, "Now is not the time!">>> It isn't so.

Changing Case in a String with Methods

name = "john smith"
print(name.title())
>>> John Smith

As you can see with the code above, the lower case string “john smith” is stored in the variable name. With the use of dot notation, we can access the method title() that tells Python to perform the title() method on the variable name. Every method is followed by a set of parentheses which can include additional informational, which are also known as arguments.

In this case, there is no need to add any additional information to the title() method. That is why they are empty. title() displays each word in the title case, where each new word gets capitalized.

There are many other methods available to use when dealing with case. For example:

book_title = "Of Mice and Men"
print(book_title.upper())
print(book_title.lower())
>>> OF MICE AND MEN>>> of mice and men

It is good to note that the lower() method is useful for storing data. You won’t want to trust the capitalization that your users will provide, so by converting the strings to lowercase before storing them you will know what to expect.

Combining or Concatenating Strings

first_name = "harry"
last_name = "potter"
full_name = first_name + " " + last_name
print(full_name)>>> harry potter

Python uses the addition symbol (+) to combine, also known as concatenate, strings. As we see above, we can use (+) to create a full name by combining the variable first_name, space, and the variable last_name, which gives us “harry potter”.

With our prior knowledge, can concatenate strings as well as use methods to provide proper casing:

first_name = "harry"print("You're a wizard " + first_name.title() + "!")>>> You're a wizard Harry!

You can also create the same result by storing the information we provided in the print statement into a variable. For example:

first_name = "harry"
message = "You're a wizard " + first_name.title() + "!"
print(message)>>> You're a wizard Harry!

Adding Whitespace to Strings with Tabs or Newlines

Whitespace refers to any nonprinting character, like spaces, tabs, and end-of-line symbols. You can add a tab to your text by combining the “backslash character — \” and the letter character “t”. It looks like this \t. For example:

#The backslash \ can easily be mistaken for a forward slash /
print("Learn Python")
print("\tLearn Python")
>>> Learn Python>>> Learn Python

You can also add a newline in a string by combining the “backslash character — \” and the letter character “n”. It looks like this \n. For example:

print("Favorite foods:\n\tSushi\n\tPizza\n\tKimchi")>>> Favorite foods:
Sushi
Pizza
Kimchi

Stripping Whitespace

Whitespace is often overlooked by those starting to program. But Whitespace can confuse your programs. To people, ‘Python’ and ‘Python ’ are the same thing, but Python will detect the extra space in ‘Python ’ and will consider it important unless you state otherwise. An excellent example that is very important to consider is checking people’s usernames when they login to a website.

Important methods to add to your memory are rstrip(), lstrip() (this is the letter character l, not the numerical character 1 but they can easily be confused with one another), and strip(). An example of their use:

personal_hero = "Ronald McDonald    "
description = " is cool"
print(personal_hero + description)
print(description + personal_hero)
>>> Ronald McDonald is cool>>> is coolRonald McDonald print(personal_hero.rstrip() + description.lstrip())
print(description.lstrip() + personal_hero.rstrip())
>>> Ronald McDonaldis cool>>> is coolRonald McDonaldprint(personal_hero.strip() + description.strip())
print(description.strip() + personal_hero.strip())
>>> Ronald McDonaldis cool>>> is coolRonald McDonald

As you can see in the above example, by using rstrip(), lstrip(), or strip() you can remove whitespacing from any of the string data types. rstrip() targets whitespacing on the right, hence the “r” in rstrip(). lstrip() targets whitespacing on the left, hence the “l” in lstrip(). And strip() targets both sides of the string data type.

Keep in mind that the changes made through those methods, rstrip(), lstrip(), and strip(), are only temporary and apply to that one instance where we called for it. If you want to remove the white space from the string permanently, you need to store the stripped value back into itself. For example:

cartoon_character = "    Goofy"
cartoon_character = cartoon_character.lstrip()
print(cartoon_character)>>> Goofy

Avoiding Syntax Errors with Strings

Syntax errors are common to have when you write programs. Syntax errors occur when Python doesn’t recognize a part of your program as valid Python code. For example:

good_apostrophe = "It's a great day!"
bad_apostrophe = 'It's a great day!'
print(good_apostrophe)>>> It's a great day!print(bad_apostrophe) #You will receive an error similar to the one belowFile "file_name.py", line 2
bad_apostrophe = 'It's a great day!'
^
SyntaxError: invalid syntax

The reason why you will receive an error is that Python won’t be able to identify where the string is supposed to end.

Numbers

Numbers are about as common as strings in programming. You can use it to represent data, store information in a web application, and a lot more. You don’t have to be a mathematician to program, but a basic understanding of math is considered a plus.

Integers

In Python, you are able to add (+), subtract (-), multiply (*), and divide (/) any number. For example:

10 + 10>>> 20100 - 10>>> 9012 * 12>>> 144144 / 12>>> 12.0

You are also able to produce exponents:

2 ** 2>>> 43 ** 3>>> 27

Many programming languages support the order of operations. If that is unfamiliar to you, the way I learned it was using the acronym “PEMDAS”. P — Parenthesis, E — Exponent, M — Multiplication, D — Division, A — Addition, and S — Subtraction. That is the order of priority when they are all combined into one expression. For example:

10 - 2 * 2>>> 6(10 - 2) * 2>>> 16

Floats

Floats are numbers with a decimal point. Although floats can perform unexpected results. If you do catch any odd results, do not fret as they are of little concern. For example:

0.2 + 0.2>>> 0.4 # expected5 * 0.2>>> 1.0 # expected0.1 + 0.2>>> 0.30000000000000004 # unexpected

Avoiding Type Errors with the str() Function

favorite_number = 24
secret_message = "My favorite number is: " + favorite_number
print(secret_message) Traceback (most recent call last):
File "file_name.py", line 2, in <module>
secret_message = "My favorite number is: " + favorite_number
TypeError: Can't convert 'int' object to str implicitly

A type error is when Python can’t recognize the type of information you are using. The value of favorite_number stores a number data type. But the variable secret_message uses the string data type. You can’t mix different data types when it comes to Python variables. To fix this you can wrap the variable in the str() function, which tells Python to represent non-string values as strings. For example:

favorite_number = 24
secret_message = "My favorite number is: " + str(favorite_number)
print(secret_message)>>> My favorite number is: 24

Comments

As your programs get longer and more complicated, adding comments to your code that describes your overall approach will be helpful. Comments are ignored in every programming language and are written specifically for the programmers.

#You've seen these before
print("Comments are extremely useful")
>>> Comments are extremely useful

Comments allow you to summarize what the code does. I’ve been told by numerous programmers to either “write a lot of comments to help describe the code” or that the “code itself must be able to describe itself through how you name your functions, variables, etc.”. At the end of the day, do your best to make your code easy for the programmers to read. Some say that shorter code is more efficient code. But computers are getting faster and faster every day, at this point, it’s best to just make sure you’ve written code that works first before having to refactor (adjust) it.

Zen of Python

import thisThe Zen of Python, by Tim PetersBeautiful is better than ugly.
Explicit is better than implicit.
Simple is better than complex.
Complex is better than complicated.
Flat is better than nested.
Sparse is better than dense.
Readability counts.
Special cases aren't special enough to break the rules.
Although practicality beats purity.
Errors should never pass silently.
Unless explicitly silenced.
In the face of ambiguity, refuse the temptation to guess.
There should be one-- and preferably only one --obvious way to do it.
Although that way may not be obvious at first unless you're Dutch.
Now is better than never.
Although never is often better than *right* now.
If the implementation is hard to explain, it's a bad idea.
If the implementation is easy to explain, it may be a good idea.
Namespaces are one honking great idea -- let's do more of those!

Typing out “import this” will provide you with the Python community’s core philosophy. It helped me get an idea of how Python programmers think, so I hope it helps you as well.

--

--