Friday, July 30, 2021

Stack Abuse: How to Join/Concatenate/Append Strings in Python

Introduction

In this short tutorial, we'll take a look at how to concatenate strings in Python, through a few different approaches.

It's worth noting that strings in Python are immutable - a string object in memory cannot be changed once created:

newString = "Some new string"

If you'd like to change this string in any way - under the hood, a new string with those changes is created. The same applies to concatenating strings - a new object must be created in memory.

String Concatenation and String Appending

Concatenation of strings refers to joining two or more strings together, as if links in a chain. You can concatenate in any order, such as concatenating str1 between str2 and str3.

Appending strings refers to appending one or more strings to the end of another string.

In some cases, these terms are absolutely interchangeable. Appending strings is the same operation as concatenating strings at the end of another. Let's begin with the simplest way of concatenating/appending two (or more) strings.

Concatenate or Append Strings with The + Operator

In Python, a string is a list of characters, which means that the + operator can be used to add their constituent elements together in a new list:

title = "Prof. "
name = "Richard Feynman"

result = title + name
print(result)

This results in:

Prof. Richard Feynman

This operator doesn't limit the amount of strings which can be added together, so you can easily join a large number of strings:

string1 = "Concatenating"
string2 = "strings"
string3 = "in Python"
string4 = "is easy!"

print(string1 + string2 + string3 + string4)

Though, if your aim is to construct a sentence from a list of strings such as this, concatenating them manually, and without special characters is both inefficient and produces an unintelligible output:

Concatenatingstringsin Pythonis easy!

It'd be much more sensible to iterate through a list of strings, and add them together with a whitespace between each concatenated string:

strings = ["Concatenating", "strings", "in Python", "is easy!"]

result = ""
for string in strings:
    result += string + " "

print(result)

This results in:

Concatenating strings in Python is easy! 

A shorthand operator you can use to concatenate two strings is +=, just like in the previous example. This saves you from the trouble of having to create a new variable to store the results, as you can reuse one of the existing reference variables to assign to the new object in memory:

string1 = "one"
string2 = "two"

string1 += string2
print(string1) # Output: onetwo

Limitation of the + Operator

The main limitation of the + operator is the fact that you can't mix-and-match types. You can't add an integer to a list of characters, for instance:

print("some string" + 2)

Many languages, such as JavaScript and Java pick up on this, and would automatically convert the integer into a string (match the types) and perform the concatenation, though, Python would throw a TypeError:

TypeError: can only concatenate str (not "int") to str

However, there is an easy workaround - you can use Python's built-in str() function which converts compatibile data types into a string. Let's add some integers to our strings list and box all of the items with a str() in case there are non-string elements:

strings = ["Concatenating", "strings", "in Python", "is easy!", 5, 2]

result = ""
for string in strings:
    result += str(string) + " "

print(result)

This results in:

Concatenating strings in Python is easy! 5 2 

Concatenate or Append Strings with The * Operator

If you want to create a new string by replicating a string n amount of times and appending it, you can achieve this with the * operator:

string = "w"

print(string * 3) # Output: www

This can be even more useful when combined with the + operator:

print("w"*3 + "." + "stackabuse.com")

Which results in:

www.stackabuse.com

Concatenate or Append Strings with The % Operator

Again, concatenation doesn't necessarily mean we're adding a string to the end. Using the % operator, we can perform string interpolation. By adding % in a string as a marker, we can replace the markers with concrete strings later on:

string = "This %s is a %s string" % ("here", "random")

print(string)

This should output:

This here is a random string

Similarly enough, you can use other markers for other data types:

  • %d - for integer representation:
string = "This is a string%d" % (1)
print(string) # Output: This is a string
  • %c - for character representation:
string = "This string starts with a %c" % ('T')
print(string) # Output: This string starts with a T
  • %f - for floating number:
string = "There is a %f percent chance that you'll learn string concatenation in Python after reading this article" % (99.99)
print(string) # Output filled 99,990000 in %f place

Note: If you wish to explicitly mark how many digits should the number be rounded to (say 2), you can achieve it with: %.2f.

If you'd like to read more about formatting strings in Python and the different ways to do it, read our Guide to Formatting Strings in Python 3's f-Strings.

Concatenating Strings With the join() Method

The join() method takes an iterable as an argument and returns a string created by joining the elements of that iterable. It's worth noting that these have to be strings - each element is not inherently converted using str(), unlike our own method from before.

Additionally, a separator is used to define the separator between the joined strings, and it's the base string we call join() on:

my_list = ["1", "2", "3", "4"] # List - iterable
string_from_list = "-".join(my_list) # The separator is "-"

print(string_from_list)

This should output:

1-2-3-4

In a lot of cases, the separator is just a whitespace, so you'll commonly be seeing:

" ".join(iterable)

Implementing a Custom join() Method

Since the built-in join() method might behave a bit differently than you might've expected, let's implement our own join() method with an adjustable separator.

We'll want it to be able to handle 2D lists as well, so if a list contains another list within itself - it's flattened to a 1-dimensional list, before joined:

import itertools

def join(iterable, separator):
    # Empty string to hold result
    result = ""
    # Flatten 2D potentially 2D list into 1D
    iterable = list(itertools.chain(*iterable))
    # Concatenate strings with separator
    for string in iterable:
        result += str(string) + separator
    return result
    

string = join(['a', 'b', 'c'], ' ')
string2 = join(['a', ['b', 'c'], 'd'], ' ')

print(string)
print(string2)

This results in:

a b c 
a b c d 

Concatenating Strings Using Space

A simple way to concatenate strings, usually only when you're printing them is to leverage the space bar. This approach is commonly used only for printing, since assigning it to an object in memory is easy, but awkward:

print("Concat" " strings" " using Space")

If you'd like to avoid using whitespaces in the strings, you can add commas (,) between each element:

print("Concat", "strings", "using Space")

Both of these result in:

Concat strings using Space

If you'd like to assign them to a variable, you're free to do so, and they'll automatically be concatenated into a single string:

string = "this " "is " "a " "big " "string"
print(type(string))
print(string)

This results in:

<class 'str'>
this is a big string

You can even do multi-line strings. To achieve this, we add a \ to the end of each line to let Python know there's more than one line:

multi_line_string = "this " "string " \
                                  "is coded in " "three lines " \
                          "but printed in one"
                                  
print(multi_line_string)

This results in:

this string is coded in three lines but printed in one

Though, this approach is fiddly and awkward, and others are preferred.

Note: The same effect cannot be achieved with variables, only string literals:

string1 = "one string"
string2 = "two string"

final_string = string1 string2

This results in:

File "<string>", line 4
    final_string = string1 string2
                           ^
SyntaxError: invalid syntax

Conclusion

Joining/Appending/Concatenating Strings in Python is fairly simple and like everything related to Python, there are many ways to do it. It just comes down to your needs and preferences.

In this short tutorial, we've taken a look at some of the ways to concatenate strings



from Planet Python
via read more

No comments:

Post a Comment

TestDriven.io: Working with Static and Media Files in Django

This article looks at how to work with static and media files in a Django project, locally and in production. from Planet Python via read...