String Concatenation and Formatting Intermediate Python Tutorial part 2




Welcome to part 2 of the intermediate Python programming tutorial series. In this part, we're going to talk about strings. Strange that we find such a topic in an intermediate series, but it's probably one of the most common things done improperly.

To begin, recall that we have some major principles when it came to defining "intermediate" python. Two of them were that our code needs to be efficient and scale, and another was that others should be able to easily understand and use our code. These two principles come into contention when it comes to string operations. When concatenating strings, we can do the following:

names = ['Jeff', 'Gary', 'Jill', 'Samantha']

for name in names:
    statement = 'Hello there ' + name
    print(statement)
Hello there Jeff
Hello there Gary
Hello there Jill
Hello there Samantha

This is easily read, but unfortunately not the ideal choice. Some people will conceed and let you do it if you're only adding two strings together, and that's it. Instead, you should be using .join:

names = ['Jeff', 'Gary', 'Jill', 'Samantha']

for name in names:
    statement = ' '.join(['Hello there', name])
    print(statement)
Hello there Jeff
Hello there Gary
Hello there Jill
Hello there Samantha

The reason for this is it scales better. When we use the +, we're creating new strings. A more impactful example of this might be if we're just trying to print out a string list of all of the names:

names = ['Jeff', 'Gary', 'Jill', 'Samantha']
print(', '.join(names))
Jeff, Gary, Jill, Samantha

Another fairly common string joining task is with file paths. It can be very tempting to do something like:

/starting/file/path + '/' + filename

As you may have guessed, this is not the correct method. Instead, we use os.path.join. For example:

#             double back-slash for window's nonsense.
location_of_files = 'C:\\Users\\H\\Desktop\\Intermediate Python'
file_name = 'example.txt'

with open(os.path.join(location_of_files, file_name)) as f:
    print(f.read())

Next, let's talk about string formatting. Let's consider that you want to insert variables into a string, like:

____ bought ____ apples today!

...where we want to fill in the blanks, with python variables:

who = 'Gary'
how_many = 12

So we want the sentence to be Gary bought 15 apples today!. Again you may be tempted to break out the + sign. You may even want to bring out the %s. Neither! Instead, we use {}, like so:

who = 'Gary'
how_many = 12

print('{} bought {} apples today!'.format(who, how_many))

There are more things we can do with string formatting, but I consider it to be beyond the scope of this series. For more information on strings, check out the strings docs

That's enough on strings for now. Next, let's talk about the standard library: argparse, for adding command-line options to your Python programs.

The next tutorial:





  • Intermediate Python Programming introduction
  • String Concatenation and Formatting Intermediate Python Tutorial part 2
  • Argparse for CLI Intermediate Python Tutorial part 3
  • List comprehension and generator expressions Intermediate Python Tutorial part 4
  • More on list comprehension and generators Intermediate Python Tutorial part 5
  • Timeit Module Intermediate Python Tutorial part 6
  • Enumerate Intermediate Python Tutorial part 7
  • Python's Zip function
  • More on Generators with Python
  • Multiprocessing with Python intro
  • Getting Values from Multiprocessing Processes
  • Multiprocessing Spider Example
  • Introduction to Object Oriented Programming
  • Creating Environment for our Object with PyGame
  • Many Blobs - Object Oriented Programming
  • Blob Class and Modularity - Object Oriented Programming
  • Inheritance - Object Oriented Programming
  • Decorators in Python Tutorial
  • Operator Overloading Python Tutorial
  • Detecting Collisions in our Game Python Tutorial
  • Special Methods, OOP, and Iteration Python Tutorial
  • Logging Python Tutorial
  • Headless Error Handling Python Tutorial
  • __str__ and __repr_ in Python 3
  • Args and Kwargs
  • Asyncio Basics - Asynchronous programming with coroutines