In the following article, we will introduce strings and characters in Python. Most importantly, we will look at various strings append/concatenate methods in Python.
Python’s string data type stores a group of characters or a single character. Strings are the sequences of characters that are enclosed within a single or double quote. A character is a string that is of length equal to one. For instance, the English language has 26 characters. From them, a string like – “this article will cover string append techniques” can be formed.
Note: Python’s string type uses the Unicode Standard for representing characters, which lets Python programs work with all kinds of different possible characters.
string = "this is a random string" # a character
character = "a" # a character
grinning_face = "?" #unicode allows us to use emojis too!
You can read an interesting article on string compression here. We should look at various methods/ways to append or concatenate strings in Python.
Different ways to append strings
Here are some of the methods to append strings in Python.
Using the f-strings
Using f-strings, we can append two or more strings together.
string1 = "The grass is always greener"
string2 = "on the other side of the fence."
print(f"Concatenated string: {string1} {string2}")
Using the format method
Using the format method of Python, we can append two or more strings together. However, its working is similar to that of f-strings; however, it is slower than it.
string1 = "Tell me and I forget."
string2 = "Teach me and "
string3 = "I remember. Involve me and I learn."
print("Concatenated string: {} {} {}".format(string1, string2, string3))
Using the join method
We can also append or concatenate strings using the join method. However, the join method joins items of an iterable into a string. Hence, to use the join method, strings have to be converted into an iterable.
string1 = "The greatest glory in living lies not in never falling, "
string2 = "but in rising every time we fall."
print(''.join([string1, string2])
Using the ‘ + ‘ operator
The ‘ + ‘ operator can concatenate two or more strings together. Let’s look at an example.
string1 = "The greatest glory in living lies not in never falling, "
string2 = "but in rising every time we fall."
print(string1 + string2)
Using the __add__ function
Using __add__ function is same as using ‘ + ‘ operator
string1 = "The greatest glory in living lies not in never falling, "
string2 = "but in rising every time we fall."
print(string1.__add__(string2))
Using the ‘ += ‘ operator
We can append two or more strings together using the ‘ +=’ operator. For instance:
string1 = "You have brains in your head. "
string2 = "You have feet in your shoes."
string3 = " You can steer yourself any direction you choose."
string1 += string2
string1 += string3
print(string1)
By keeping the strings on the same line
Another unique way is to assign all the strings to append into a variable, keeping all of them in the same line. Let’s see how we can do this.
string = "Believe you can" "and you're halfway there."
print(string)
Using the string module’s Template class
The string module of Python has a template class that can be used to append strings together. However, it is slow, and code lines are increased for simple tasks like string concatenation.
from string import Template
string1 = "The question isn't who is going to let me;"
string2 = "it's who is going to stop me."
string = Template("$string1 $string2")
print(new.substitute(string_one=string1, string_one=string2))
Using the format specifier
Format specifier can append or concatenate two or more strings together.
string1 = "Never let the fear of striking out"
string2 = "keep you from playing the game."
print('%s %s' % (string1, string2))
Append byte strings in Python
In python3
In python3, byte strings can be concatenated using the join method. However, you can use any of the methods specified above.
bytestring1 = b"\x6E"
bytestring2 = b"\x6F"
joined_bytestrings = b''.join([bytestring1,bytestring2])
print(joined_bytestrings)
In python2
In python2, byte strings can be concatenated using format specifiers.
bytestring1 = b"\x6E"
bytestring2 = b"\x6F"
print("%s%s" %(bytestring1,bytestring2))
Inserting characters at the start and end of a string
We can simply insert characters at the start and end of a string using the ” + ” operator. For instance:
string = "nima"
string = "a"+string+"l"
print(string)
Append strings in pandas
We can easily append strings in pandas. For instance, if we have a data frame with state and code information.
import pandas as pd
df = {
"State": [
"Alabama",
"Arizona",
"Alaska",
"Arkansas",
"California",
],
"Code": ["AL", "AZ", "AL", "AR", "CA"],
}
df = pd.DataFrame(df, columns=["State", "Code"])
print(df)
Now, if we want to add “IN-” before the code column contents, we can do so as follows.
df["Code"] = "US-" + df["Code"].astype(str)
print(df)
FAQs on Append Strings in Python
You can use the join method of Python to do so.string1 = "firststring"
)
string2 = "secondstring"
print(" ".join([string1,string2])
Output: firststring secondstring
You can use the join method of Python to do so.string1 = "firststring"
)
string2 = "secondstring"
print("".join([string1,string2])
Output: firststringsecondstring
Conclusion: Which strings append method is best?
It is important to realize that optimization should be done only if necessary. It is advisable to keep your code more readable and pythonic. However, for comparison purposes:
- For python3 join method outperforms others.
- For python2 ‘ + ‘ or ‘ % ‘ operator are better choice.