String Concatenation in Python: Using the + Operator, f-strings, and join()

In Python, you often need to combine multiple strings into a new one. Examples include combining a first and last name to create a full name, or assembling a log message. There are several ways to concatenate strings, such as the + operator, f-strings, and the join() method. This article explains each method and when to use them.


目次

1. Concatenation with the + Operator

The most intuitive and basic method is to use the + operator (addition operator). Connecting strings with + concatenates them in order.

# Combine 'Hello' and 'World'
greeting_part1 = "Hello"
greeting_part2 = "World"

# Concatenate spaces as strings too
full_greeting = greeting_part1 + ", " + greeting_part2 + "!"

print(full_greeting)

Output:

Hello, World!

This method is handy for simply joining two or three strings.


2. Concatenating Strings and Numbers (TypeError and f-strings)

The most common error when using the + operator is trying to concatenate a string (str) and a number (int or float) directly.

user_name = "Agent"
user_id = 777

# TypeError: can only concatenate str (not "int") to str
# log_message = "User: " + user_name + ", ID: " + user_id 

Python cannot automatically concatenate different data types with +. To solve this, you must explicitly convert the number to a string.

Using str() (Traditional Method)

Use the str() function to convert the number to a string before concatenating with +.

# Convert 777 to "777" with str(user_id)
log_message = "User: " + user_name + ", ID: " + str(user_id)

print(log_message)

Output:

User: Agent, ID: 777

Using f-strings (Recommended Method)

While using str() works, the code becomes hard to read when there are many variables and + symbols. In such cases, f-strings (Formatted String Literals) are strongly recommended.

Place f before the starting quote of the string and embed {variable_name} inside. Python will automatically convert the variable’s value to a string and insert it.

user_name = "Agent"
user_id = 777
login_attempts = 3.5 # Float works too

# Use f-string
log_message_f = f"User: {user_name}, ID: {user_id}, Attempts: {login_attempts}"

print(log_message_f)

Output:

User: Agent, ID: 777, Attempts: 3.5

This is much more concise and readable than using + and str().


3. Concatenating Lists with the join() Method

When concatenating many strings generated in a loop (such as a list), using the + operator repeatedly is inefficient. In these cases, the standard approach is to use the join() method.

Syntax: "separator".join(list_of_strings)

This method returns a single string where each string in the list is connected by the “separator”.

# Log fragments stored in a list
log_parts = ["2025-11-11", "ERROR", "AuthService", "Login failed"]

# 1. Join with comma (CSV)
csv_line = ",".join(log_parts)
print(f"CSV: {csv_line}")

# 2. Join with hyphen
hyphen_line = " - ".join(log_parts)
print(f"Log: {hyphen_line}")

# 3. Join without separator
no_space_line = "".join(log_parts)
print(f"No Space: {no_space_line}")

Output:

CSV: 2025-11-11,ERROR,AuthService,Login failed
Log: 2025-11-11 - ERROR - AuthService - Login failed
No Space: 2025-11-11ERRORAuthServiceLogin failed

join() is very fast and should be your first choice when concatenating many elements.


Summary

Use these three methods for string concatenation depending on your purpose.

  • + Operator: For simply joining a small number (2-3) of strings.
  • f-string (f"..."): For embedding variables (especially numbers) into strings. Highly readable and recommended.
  • join() Method: For efficiently joining many strings stored in a list or iterable with a specific separator.
よかったらシェアしてね!
  • URLをコピーしました!
  • URLをコピーしました!

この記事を書いた人

私が勉強したこと、実践したこと、してることを書いているブログです。
主に資産運用について書いていたのですが、
最近はプログラミングに興味があるので、今はそればっかりです。

目次