深度阅读

How to append a string in Python

作者
作者
2023年08月22日
更新时间
8.99 分钟
阅读时间
0
阅读量

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.

博客作者

热爱技术,乐于分享,持续学习。专注于Web开发、系统架构设计和人工智能领域。