Question

How to Concatenate Strings in Python: str and String-Like Values

ruststringstring-concatenation

Question

In Python, how can I concatenate these combinations of text values?

  • str and str
  • String and str
  • String and String

I want to understand the correct way to join string values together, especially when the types may not appear identical.

Short Answer

By the end of this page, you will understand how string concatenation works in Python, how to join normal string values using +, what to do when values are not both plain str, and how to avoid common type-related mistakes.

Concept

In Python, string concatenation means combining text values into a single string.

The most common way to concatenate two strings is with the + operator:

first = "Hello, "
second = "world"
result = first + second
print(result)

This produces:

Hello, world

The important rule

Both values must be strings for + to work directly in string concatenation.

Python's built-in text type is str. So when you concatenate text in Python, you are usually working with str objects.

a = "foo"
b = "bar"
print(a + b)  # foobar

What about String?

In Python, String with a capital S is not a built-in type like it is in some other languages such as Java or C#. The real built-in string type is str.

So if you see String, one of these is usually true:

  • it is just being used informally to mean “a string”
  • it refers to a custom class in someone else's code
  • it comes from another library and is not a normal Python str

If a value is not a real str, you may need to convert it before concatenation:

result = str(value1) + str(value2)

Why this matters

In real programs, text often comes from:

  • user input
  • APIs
  • files
  • databases
  • custom objects

You often need to combine these values into messages, file paths, labels, logs, or output. Understanding when values are true strings and when they need conversion helps you avoid TypeError and write clearer code.

Mental Model

Think of a Python string as a strip of text on paper.

  • Concatenation means taping two strips together end to end.
  • If both pieces are already text, Python can join them easily.
  • If one piece is not actually text, Python first needs you to turn it into text.

So:

  • str + str → tape works immediately
  • non-str + str → convert first, then tape

If you try to tape a number or custom object directly onto a text strip, Python stops and asks you to be explicit.

Take Quiz

Syntax and Examples

Basic syntax

result = string1 + string2

Both string1 and string2 should be str values.

Example: str and str

first_name = "Ada"
last_name = "Lovelace"
full_name = first_name + " " + last_name

print(full_name)

Output:

Ada Lovelace

This works because all parts are strings.

Example: converting another type to str

age = 28
message = "Age: " + str(age)

print(message)

Output:

Age: 28

Without str(age), Python would raise an error because age is an integer, not a string.

Example: a custom String-like object

class String:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return self.value

s1 = String("Hello")
s2 = String("World")

result = str(s1) + " " + str(s2)
print(result)

Output:

Hello World

This works because str(s1) and str(s2) convert the custom objects into normal Python strings.

Better alternative for mixed values: f-strings

name = "Sam"
score = 95
message = f"{name} scored {score}"
print(message)

Output:

Sam scored 95

F-strings are often easier to read than repeated + operations.

Step by Step Execution

Consider this example:

class String:
    def __init__(self, value):
        self.value = value

    def __str__(self):
        return self.value

left = String("Hello")
right = " there"
result = str(left) + right
print(result)

Step by step

  1. A custom class named String is defined.
  2. The __init__ method stores the text in self.value.
  3. The __str__ method tells Python how to turn the object into a normal string.
  4. left = String("Hello") creates a String object.
  5. right = " there" creates a normal Python str.
  6. str(left) calls left.__str__() and returns "Hello".
  7. Python evaluates "Hello" + " there".
  8. Both values are now str, so concatenation succeeds.
  9. result becomes "Hello there".
  10. print(result) outputs the final text.

Output:

Hello there

Real World Use Cases

String concatenation is used constantly in real programs.

Building messages

username = "maria"
message = "Welcome, " + username

Used in command-line tools, web apps, and notifications.

Creating log output

status = "OK"
log_line = "Service status: " + status

Useful for debugging and monitoring.

Combining file name parts

name = "report"
extension = ".txt"
filename = name + extension

Common in scripts that generate files.

Formatting data for display

city = "Paris"
country = "France"
label = city + ", " + country

Used in UI labels, exports, and reports.

Joining API or database values

first = "Grace"
last = "Hopper"
full = first + " " + last

Useful when displaying structured data as readable text.

Take Quiz

Real Codebase Usage

In real projects, developers often concatenate strings in a few common ways.

Simple + for small, direct cases

error_prefix = "Error: "
message = error_prefix + "invalid input"

This is fine when combining only a small number of string values.

F-strings for readability

user = "alice"
count = 3
text = f"User {user} has {count} notifications"

This is very common in production code because it is clear and concise.

''.join(...) for many pieces

parts = ["Py", "thon", "3"]
result = "".join(parts)

This is preferred when joining many strings from a list or loop.

Validation before concatenation

Developers often check values before building strings:

def greet(name):
    if name is None:
        return "Hello, guest"
    return "Hello, " + str(name)

This guard clause prevents errors and handles missing data.

Converting custom objects explicitly

def build_label(value):
    return "Value: " + str(value)

This makes code safer when inputs may not already be strings.

Common Mistakes

1. Concatenating a string with a non-string

Broken code:

age = 30
text = "Age: " + age

This raises:

TypeError

Fix:

text = "Age: " + str(age)

2. Assuming String is a built-in Python type

Broken idea:

value = String("hello")

This fails unless String was defined somewhere.

In Python, the built-in string type is:

str

3. Forgetting spaces when concatenating

first = "Hello"
second = "World"
print(first + second)

Output:

HelloWorld

Fix:

print(first + " " + second)

4. Using + repeatedly inside large loops

This can be inefficient for many pieces of text.

Less ideal:

result = ""
for part in ["a", "b", "c"]:
    result += part

Better:

parts = ["a", "b", "c"]
result = "".join(parts)

5. Relying on implicit conversion that Python does not do

Python does not automatically convert most types to strings during + concatenation.

Broken code:

price = 19.99
label = "Price: $" + price

Fix:

label = "Price: $" + str(price)

Comparisons

ApproachBest forExampleNotes
+Joining a small number of strings"a" + "b"Simple and readable for short cases
str() + +Mixed types"Age: " + str(age)Explicit conversion avoids errors
f-stringsReadable formattingf"Age: {age}"Usually the clearest choice
"".join(...)Many strings in a list"".join(parts)Better for repeated joining

str vs String

NameIn Python?Meaning
strYesBuilt-in Python string type
StringNot built-inUsually a custom class or borrowed terminology

+ vs f-strings

Feature+f-string
Works with plain stringsYesYes
Handles non-strings directlyNoYes, by formatting them
ReadabilityGood for simple casesBetter for mixed values
Best useSmall joinsBuilding messages and output
Take Quiz

Cheat Sheet

Quick rules

  • Python's built-in string type is str
  • Concatenate strings with +
  • Both sides of + must be strings for string concatenation
  • Use str(value) to convert non-string values
  • Use f-strings for cleaner mixed-value formatting
  • Use "".join(list_of_strings) for many string parts

Common patterns

"Hello" + "World"
"Hello " + name
"Age: " + str(age)
f"Age: {age}"
"".join(["a", "b", "c"])

If you see String

  • It is not a built-in Python type
  • Check whether it is a custom class
  • Convert with str(...) if needed

Avoid

"Age: " + 25

Prefer

"Age: " + str(25)

or

f"Age: {25}"

FAQ

Is String a built-in type in Python?

No. Python's built-in text type is str. String is not a standard built-in type.

How do I concatenate two strings in Python?

Use the + operator:

result = "Hello" + "World"

Why do I get a TypeError when using +?

Because one of the values is not a string. Convert it first with str(...) or use an f-string.

Should I use + or f-strings?

Use + for very simple string-to-string joining. Use f-strings when combining text with variables or other types.

What is the best way to join many strings?

Use "".join(...) when you have a list of strings.

Can custom objects be concatenated like strings?

Not directly unless they behave like strings. Usually you should convert them with str(obj) first.

Does Python automatically convert numbers to strings during concatenation?

No. You must convert them yourself with str(...) or use an f-string.

Take Quiz

Mini Project

Description

Build a small Python program that creates user-friendly profile messages by combining text values. This demonstrates plain string concatenation, converting non-string values, and working with a custom string-like object.

Goal

Create formatted profile output using str, +, and str(...) conversion safely.

Requirements

  • Create a normal Python string for a user's first name
  • Create an integer value for the user's age
  • Define a custom String class with a __str__ method
  • Use concatenation to build one complete profile message
  • Print the final message without raising a type error
Take Quiz

Keep learning

Related questions

View more