Skip to content
Bronze 5 min read · Strings 2 practice problems ↓

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

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

FunctionWith a null inputExample
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 skippedconcat_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

PySparkSpark SQL

Input: customers

idfirstlastcityphone
1" ana "Raopune98-765-43
2BonullDELHI12-345
3cyLeeMumbainull
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

JobFunctionNotes
Remove spacestrim, ltrim, rtrimRemoves spaces only; tabs and non-breaking spaces need regexp_replace(c, r"^\s+|\s+$", "")
Change caselower, upper, initcapLower-case both sides before comparing or joining on text
Cutsubstring(c, pos, len)1-based. A negative pos counts from the end: substring(c, -4, 4) is the last 4 characters
Splitsplit(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 piecesplit(c, "-")[0] or F.split(c, "-").getItem(0)0-based, unlike substring
LengthlengthCharacters, not bytes
Padlpad(c, 5, "0"), rpadZero-pad codes; also truncates values longer than the width
Replacereplace (literal, Spark 3.5+), regexp_replace, translatetranslate(c, "-.", "") deletes characters one by one
Findinstr, locate, contains, startswith, likeinstr 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.

Why this matters: every built-in function runs inside the JVM on whole batches of rows, and CatalystCatalyst: Spark's query optimizer. It rewrites your DataFrame code into a faster equivalent plan before running it. Learn more → can optimise around it. A Python UDFUDF: User-defined function: your own Python function applied to each row. Flexible but much slower than built-in functions. Learn more → that does the same .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 when last is null, so that row never matches in a join. Use concat_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, while substring and element_at count from 1.
  • Joining on raw text — "Pune" and "pune " never match, so those rows silently drop out of the join. Apply F.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.
  • trim removes spaces only; tabs and non-breaking spaces need regexp_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 with replace (Spark 3.5+), and patterns with regexp_replace.

Interview prep

THE QUESTION

"Build a customer key from first name, last name and postcode. Some last names are null."

Use 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?"
Without a separator, different inputs can produce the same string: "ab" + "c" and "a" + "bc" both give "abc". A separator that cannot appear in the data (or hashing a delimited string) keeps keys unique.
Scenario"Names come with stray spaces and mixed case, and joins on them miss matches. What do you do?"
Normalise once before joining: 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."
Spark positions start at 1. Position 0 happens to behave like 1, which hides the mistake, but negative and other offsets do not follow Python slicing. Write substring(col, 1, 3).

Check yourself

3 questions

What 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 read
Parsing dates and timestamps
to_date, to_timestamp and date_format patterns, and why yyyy and YYYY are not the same.

Related lessons

Previous: cast and schemas

Primary sources: String functions · functions.concat_ws