String functions
Names come in mixed case, ids have stray spaces, addresses need gluing together. Spark has a function for each of these jobs. This lesson covers joining strings, cutting them up, cleaning them, and the null trap that makes joined keys silently stop matching.
Step 1 · PySpark functions · Bronze · Clean and type, lesson 2 of 5
On this page
Show code in
Every code block on the page follows this.
Read first: select (skip if you know it)
In plain words first
Think of the small jobs you do to text in a spreadsheet: glue first and last name together with a space, cut the first three letters of a code, trim stray spaces, make everything lower case. Each of those is one Spark function, applied to every row of a column at once.
concat vs concat_ws
| Function | With a null input | Example |
|---|---|---|
concat(a, b, ...) | The whole result is nullnull: A missing or unknown value. Any comparison with null gives null, so filters treat it as false. Learn more → | concat("Bo", " ", null) → null |
concat_ws(sep, a, b, ...) | The null is skipped | concat_ws(" ", "Bo", null) → "Bo" |
For names, addresses and keys built from several columns, concat_ws is almost always what you want. If you build a join key with concat, rows with any null part silently stop matching.
Run the example
Input: customers
| id | first | last | city | phone |
|---|---|---|---|---|
| 1 | " ana " | Rao | pune | 98-765-43 |
| 2 | Bo | null | DELHI | 12-345 |
| 3 | cy | Lee | Mumbai | null |
from pyspark.sql import functions as F result = customers.select( "id", F.concat("first", F.lit(" "), "last").alias("with_concat"), F.concat_ws(" ", F.initcap(F.trim("first")), "last").alias("full_name"), F.upper(F.substring("city", 1, 3)).alias("city_code"), F.split("phone", "-").alias("phone_parts"), )
SELECT id, concat(first, ' ', last) AS with_concat, concat_ws(' ', initcap(trim(first)), last) AS full_name, upper(substring(city, 1, 3)) AS city_code, split(phone, '-') AS phone_parts FROM customers
Row 2 shows the null trap: with_concat is null because last is null, while full_name is "Bo". Row 1 shows why cleaning comes first: the raw value " ana " keeps its spaces inside with_concat.
The toolkit
| Job | Function | Notes |
|---|---|---|
| Remove spaces | trim, ltrim, rtrim | Removes spaces only; tabs and non-breaking spaces need regexp_replace(c, r"^\s+|\s+$", "") |
| Change case | lower, upper, initcap | Lower-case both sides before comparing or joining on text |
| Cut | substring(c, pos, len) | 1-based. A negative pos counts from the end: substring(c, -4, 4) is the last 4 characters |
| Split | split(c, pattern) | The pattern is a regexregular expression: A short pattern that describes what some text looks like, used to find, check or extract parts of strings. Learn more →: split on a dot with "\\.", not "." |
| Pick a piece | split(c, "-")[0] or F.split(c, "-").getItem(0) | 0-based, unlike substring |
| Length | length | Characters, not bytes |
| Pad | lpad(c, 5, "0"), rpad | Zero-pad codes; also truncates values longer than the width |
| Replace | replace (literal, Spark 3.5+), regexp_replace, translate | translate(c, "-.", "") deletes characters one by one |
| Find | instr, locate, contains, startswith, like | instr and locate return 1-based positions, 0 if not found |
1-based or 0-based?
SQL functions count from 1: substring, instr, locate, element_at. Arrayarray: A column that holds a list of values in each row, such as the items of one order. Learn more → indexing with brackets or getItem counts from 0. split("98-765-43", "-")[0] is "98", while element_at(split(...), 1) is also "98".
Cleaning text before a join
Text keys from two systems rarely match exactly. Normalise both sides the same way before joining: F.lower(F.trim(c)), and remove punctuation with regexp_replace when needed. A join on raw names silently drops "Pune" vs "pune " pairs.
.strip().lower() ships every row to a Python process and back, typically several times slower.Common mistakes
- Building a key with concat —
concat(first, "|", last)is null whenlastis null, so that row never matches in a join. Useconcat_ws("|", first, last), which gives"Bo". - Splitting on a dot —
split("10.0.0.1", ".")reads.as "any character" and returns empty strings instead of the four parts. Escape it:"\\."(and"\\|"for a pipe). - Picking a piece with the wrong base —
split("98-765-43", "-")[1]is"765", not"98": arrays count from 0, whilesubstringandelement_atcount from 1. - Joining on raw text —
"Pune"and"pune "never match, so those rows silently drop out of the join. ApplyF.lower(F.trim(c))to both sides first.
Key takeaways
- Put a separator between the parts of a key: without one, "ab" + "c" and "a" + "bc" build the same key.
trimremoves spaces only; tabs and non-breaking spaces needregexp_replace(c, r"^\s+|\s+$", "").lpad(c, 5, "0")zero-pads codes, but it also cuts values longer than the width.- Delete single characters with
translate, replace a literal string withreplace(Spark 3.5+), and patterns withregexp_replace.
Interview prep
THE QUESTION
"Build a customer key from first name, last name and postcode. Some last names are null."
concat_ws("|", lower(trim(first)), lower(trim(last)), postcode) so nulls do not null the key, with a separator so "ab"+"c" and "a"+"bc" do not collide. Mention that concat would return null for every row with a null part, and that normalising case and spaces first is essential for matching.Avoid: using concat. With one null input, concat returns null for the whole key.
Follow-ups · answer out loud, then open
Follow-up"Why is the separator in concat_ws important for keys?"
Scenario"Names come with stray spaces and mixed case, and joins on them miss matches. What do you do?"
F.lower(F.trim(F.regexp_replace("name", r"\s+", " "))), possibly removing accents. Join on the normalised column, and store it so every consumer uses the same rule.Trap"substring('col', 0, 3) returns the first three characters, like Python."
substring(col, 1, 3).Check yourself
3 questionsWhat is concat("a", null, "b")?
Show the answer
null. concat returns null when any input is null.
What does substring("Mumbai", 1, 3) return?
Show the answer
"Mum". substring is 1-based: start at the first character and take 3.
Why does split("a.b.c", ".") not split on dots?
Show the answer
The pattern is a regex and "." matches any character. Escape it as "\\." to split on a literal dot.
Practise this
Problems that use this, graded on hidden tests
Keep going
Up next · Clean and type · lesson 3 of 5 · 4 min readParsing dates and timestamps
to_date, to_timestamp and date_format patterns, and why yyyy and YYYY are not the same.
Related lessons
regexp_extractPySpark functions · 5 min read
cast and schemasPySpark functions · 7 min read
UDFs and pandas UDFs
Previous: cast and schemas
Primary sources: String functions · functions.concat_ws