The best way of appending a string to a string variable is to use Show
However, those who recommend having lists and appending to them and then joining those lists, do so because appending a string to a list is presumably very fast compared to extending a string. And this can be true, in some cases. Here, for example, is one million appends of a one-character string, first to a string, then to a list:
OK, turns out that even when the resulting string is a million characters long, appending was still faster. Now let's try with appending a thousand character long string a hundred thousand times:
The end string, therefore, ends up being about 100MB long. That was pretty slow, appending to a list was much
faster. That that timing doesn't include the final
Oups. Turns out even in this case, append/join is slower. So where does this recommendation come from? Python 2?
Well, append/join is marginally faster there if you are using extremely long strings (which you usually aren't, what would you have a string that's 100MB in memory?) But the real clincher is Python 2.3. Where I won't even show you the timings, because it's so slow that it hasn't finished yet. These tests suddenly take minutes. Except for the append/join, which is just as fast as under later Pythons. Yup. String concatenation was very slow in Python back in the stone age. But on 2.4 it isn't anymore (or at least Python 2.4.7), so the recommendation to use append/join became outdated in 2008, when Python 2.3 stopped being updated, and you should have stopped using it. :-) (Update: Turns out when I did the
testing more carefully that using However, this is CPython. Other implementations may have other concerns. And this is just yet another reason why premature optimization is the root of all evil. Don't use a technique that's supposed "faster" unless you first measure it. Therefore the "best" version to do string concatenation is to use + or +=. And if that turns out to be slow for you, which is pretty unlikely, then do something else. So why do I use a lot of append/join in my code? Because sometimes it's actually clearer. Especially when whatever you should concatenate together should be separated by spaces or commas or newlines. There are few guarantees in life: death, taxes, and programmers needing to deal with strings. Strings can come in many forms. They could be unstructured text, usernames, product descriptions, database column names, or really anything else that we describe using language. With the near-ubiquity of string data, it’s important to master the tools of the trade when it comes to strings. Luckily, Python makes string manipulation very simple, especially when compared to other languages and even older versions of Python. In this article, you will learn some of the most fundamental string operations: splitting, concatenating, and joining. Not only will you learn how to use these tools, but you will walk away with a deeper understanding of how they work under the hood. Splitting StringsIn Python, strings are represented as Have you guessed how those two features of strings relate to splitting functionality in Python? If you guessed that What about string immutability? This should remind you that string methods are not in-place operations, but they return a new object in memory. Splitting Without ParametersBefore going deeper, let’s look at a simple example: >>>
This is actually a special case of a Another feature of the bare call to >>>
The first thing to notice is that
this showcases the immutability of strings in Python: subsequent calls to The second—and the main—thing you should see is that the bare Specifying Separators
Where there are multiple consecutive separators (such as between “this” and “is” and between “is” and “my”), the first one will be used as the separator, and the subsequent ones will find their way into your result list as empty strings. Limiting Splits With Maxsplit
>>>
As you see above, if you set What happens
when you give a negative number as the
You were recently handed a comma-separated value (CSV) file that was horribly formatted. Your job is to extract each row into an list, with each element of that list representing the columns of that file. What makes it badly formatted? The “address” field includes multiple commas but needs to be represented in the list as a single element! Assume that your file has been loaded into memory as the following multiline string:
Your output should be a list of lists:
Each inner list represents the rows of the CSV that we’re interested in, while the outer list holds it all together. Here’s my solution. There are a few ways to attack this. The important thing is that you used
We call The first
element is What does The final part might be new: In all, we iterate through a list of strings, where each element represents each line in the multiline input string except for the very first line. At each string, we call Concatenating and Joining StringsThe other fundamental string operation is the opposite of splitting strings: string concatenation. If you haven’t seen this word, don’t worry. It’s just a fancy way of saying “gluing together.” Concatenating With the + OperatorThere are a few ways of doing this, depending on what you’re trying to achieve. The simplest and most common method is to use the plus symbol ( >>>
In keeping with the math theme, you can also multiply a string to repeat it: Remember, strings are immutable! If you concatenate or repeat a string stored in a variable, you will have to assign the new string to another variable in order to keep it. >>>
If we didn’t have immutable strings, Another note is that Python does not do
implicit string conversion. If you try to concatenate a string with a non-string type, Python will raise a >>>
This is because you can only concatenate strings with other strings, which may be new behavior for you if you’re coming from a language like JavaScript, which attempts to do implicit type conversion. Going From a List to a String in Python With .join()There is another, more powerful, way to join strings together. You can go from a list to a string in Python with the The common use case here is when you have an iterable—like a
list—made up of strings, and you want to combine those strings into a single string. Like This is a bit of a trick question. Remember that when you use >>>
Here, we join each element of the How could you make the output text more readable? One thing you could do is add spacing: >>>
By doing nothing more than adding a space to our join string, we’ve vastly improved the readability of our output. This is something you should always keep in mind when joining strings for human readability.
>>>
Using our web scraping tutorial, you’ve built a great weather scraper. However, it loads string information in a list of lists, each holding a unique row of information you want to write out to a CSV file:
Your output should be a single string that looks like this:
For this solution, I used a list comprehension, which is a powerful feature of Python that allows you to rapidly build lists. If you want to learn more about them, check out this great article that covers all the comprehensions available in Python. Below is my solution, starting with a list of lists and ending with a single string:
Here we use Tying It All TogetherWhile this concludes this overview of the most basic string operations in Python (splitting, concatenating, and joining), there is still a whole universe of string methods that can make your experiences with manipulating strings much easier. Once you have mastered these basic string operations, you may want to learn more. Luckily, we have a number of great tutorials to help you complete your mastery of Python’s features that enable smart string manipulation:
What is the best way to concatenate strings in Python?One of the most popular methods to concatenate two strings in Python (or more) is using the + operator. The + operator, when used with two strings, concatenates the strings together to form one.
How do I combine two strings in Python?Two strings can be concatenated in Python by simply using the '+' operator between them. More than two strings can be concatenated using '+' operator.
How do you concatenate 3 strings in Python?To concatenate strings, we use the + operator. Keep in mind that when we work with numbers, + will be an operator for addition, but when used with strings it is a joining operator.
How do you join a list of strings in Python?To join a list of strings into a string in Python: Specify a separator string. Call the join() method on the separator string and the list. See the merged string as a result.
|