Concatenate strings

2 snippets across 2 stacks - Python, SQL

PYPython

Join & Split

PY · Strings
Syntax
separator.join(iterable)
str.split(separator)
Example
words = ["Python", "is", "great"]
sentence = " ".join(words)
print(sentence)

csv_row = "alice,30,engineer"
fields = csv_row.split(",")
print(fields)
Output
Python is great
['alice', '30', 'engineer']

Note split() with no arguments splits on any whitespace and removes empty strings. split(',') keeps empty strings between consecutive delimiters.

SQLSQL

CONCAT / String Concatenation

SQL · String Functions
Syntax
CONCAT(str1, str2, ...)
-- or ANSI: str1 || str2
Example
SELECT
  CONCAT(first_name, ' ', last_name) AS full_name,
  first_name || ' ' || last_name AS full_name_ansi
FROM users;
Output
-- full_name     | full_name_ansi
-- Alice Johnson | Alice Johnson

Note The || operator is ANSI standard and works in PostgreSQL. MySQL uses CONCAT() only. In MySQL, CONCAT returns NULL if any argument is NULL. In PostgreSQL, || with a NULL also returns NULL. Use COALESCE to handle NULLs.

Frequently asked questions

How do you concatenate strings?
This task is covered in 2 stacks on this page: Python, SQL. The "Join & Split" snippet in Python uses `separator.join(iterable)`.
Which code does the Python example use?
The "Join & Split" snippet uses `separator.join(iterable)`, from the Strings section of the Python cheat sheet.
Which stacks cover "concatenate strings" on this page?
Python, SQL. Together they hold 2 copy-ready snippets for this task.
Is there anything to watch out for?
Yes. For "Join & Split": split() with no arguments splits on any whitespace and removes empty strings. split(',') keeps empty strings between consecutive delimiters.