How to append a string in Python
Published on Aug. 22, 2023, 12:15 p.m.
To append a string in Python, you can concatenate two separate strings using the +
operator, or use the +=
operator to update a string in place.
Here’s an example of using the +
operator:
s1 = "Hello, "
s2 = "world!"
result = s1 + s2
print(result)
Output:
Hello, world!
Here’s an example of using the +=
operator:
s1 = "Hello, "
s2 = "world!"
s1 += s2
print(s1)
Output:
Hello, world!
Note that strings are immutable in Python, so when you use the +
or +=
operator, the original strings are not modified - a new string containing the concatenated text is created.
There are also other methods for appending strings in Python, such as using the "".join()
method with a list of strings or using string formatting methods like f-strings. However, the +
and +=
operators are the most commonly used methods for concatenating strings.