Concatenate string to all elements in list Python

Stop Overusing + to Join Strings in Python

Here are 3 alternatives that will help you do more than joining strings

Frank Andrade

Oct 4·4 min read

Photo by Nadine Shaabana on Unsplash

One common task data scientists have to deal with when collecting and cleaning data is working with strings. This involves formatting as well as joining strings [also known as string concatenation].

Joining strings in Python and other programming languages is as simple as using the plus operator +. Youve probably used the code below hundreds of times to join strings in Python.

>>> str1 = "Hello "
>>> str2 = "World"
>>> str1 + str2
"Hello World"

This approach is fine. However, this becomes impractical when working with lists, dataframes, or if youre aiming for readability.

In this article, Ill show you 3 alternatives that will not only help you concatenate strings but also allow you easily join list elements, properly format strings in Python, and make debugging less complicated.

f-string

Python f-string was introduced in Python 3.6 and allows us to join strings the same way the plus operator would do; however, f-strings use curly braces {} to store a value that will be formatted into a string.

As an example lets print the sentence Python was created by Guido van Rossum and released in 1991 using f-string. In this case, we will use the name Guido van Rossum and the year 1991 as variables.

Lets have a look at the f-string syntax.

>>> name = 'Guido van Rossum'
>>> year = 1991
>>> f'Python was created by {name} and released in {year}'

It has a cleaner syntax than the + operator, isnt it?

You can also format text numbers or dates using f-string. Lets say we get todays date with the datetime library and we want to add it to a text.

>>> import datetime
>>> now = datetime.datetime.now[]
>>> f'Today is {now:%B} {now:%-d}, {now:%Y}'

Python will print Today is October 1, 2021. As a side note, the %B, %-dand %Y are format codes. You can find other time format codes available in this Python strftime cheatsheet.

Now lets format a numeric value.

>>> gpa = 3.355>>> f'His GPA is {gpa:.1f}'

Python will round the number to the first decimal and print His GPA is 3.4In this example, the .f is a format code that represents floating point numbers, so in the example, above we specified 1 digit of precision. You can find more format codes like these on this link.

Something cool about f-string is that developers keep adding new functionalities. Python introduced a brand new feature in Python 3.8 that added the = to f-strings. This simplifies the frequent print-debugging, so instead of writing the code below to print both a variable name and its value.

>>> python_version = 3.8
>>> f"python_version={python_version}"
'python_version=3.8'

You can now only write this:

>>> f"{python_version=}"'python_version=3.8'

join[]

When you want to join multiple strings stored in a list, the easiest option is to use the join[] method. You only need to specify a separator before using the join[] method.

Lets say we have the same sentence used before, but now each word is stored in a list calledwords.

words = ['Python', 'was', 'created', 'by', 'Guido', 'van', 'Rossum', 'and', 'first', 'released', 'in', '1991']

We use the join method and an empty string as a separator to build the sentence we had before.

>>> ' '.join[words]

The join[] method is not only a useful way to concatenate list elements but is also preferred over the + operator because of its performance. Thejoin[] method can be 4 times faster than using + to join strings in a list.

str.format[ ]

We can use the str.format[] to concatenate strings in Python. We only need to insert curly braces {} for every variable we want to add inside a string. The curly braces operator will help us format strings in Python.

Lets have a look.

>>> name = 'Guido van Rossum'
>>> year = 1991

>>> "Python was created by {} and released in {}".format[name, year]

One of the reasons why str.format[] is preferred over the + operator is that we dont have to explicitly convert integers into strings before concatenating. In the example above, we didnt have to convert theyear variable into a string as we would do when using the + operator.

Unfortunately, one disadvantage of using str.format[] is that the code could get quite long when dealing with many variables and long strings. This is why f-string is preferred over str.format[].

Thats it! Those are the 3 alternatives to joining strings with the + operator in Python. Use them wisely to write better Python code.

Join my email list with 3k+ people to get my Python for Data Science Cheat Sheet I use in all my tutorials [Free PDF]

If you enjoy reading stories like these and want to support me as a writer, consider signing up to become a Medium member. Its $5 a month, giving you unlimited access to thousands of Python guides and Data science articles. If you sign up using my link, Ill earn a small commission with no extra cost to you.

Join Medium with my referral link Frank Andrade

As a Medium member, a portion of your membership fee goes to writers you read, and you get full access to every story

frank-andrade.medium.com

Video liên quan

Chủ Đề