pyspark.sql.functions.lpad#

pyspark.sql.functions.lpad(col, len, pad)[source]#

Left-pad the string column to width len with pad.

New in version 1.5.0.

Changed in version 3.4.0: Supports Spark Connect.

Parameters
colColumn or column name

target column to work on.

lenColumn or int

length of the final string.

Changed in version 4.0.0: pattern now accepts column.

padColumn or literal string

chars to prepend.

Changed in version 4.0.0: pattern now accepts column.

Returns
Column

left padded result.

Examples

Example 1: Pad with a literal string

>>> from pyspark.sql import functions as sf
>>> df = spark.createDataFrame([('abcd',), ('xyz',), ('12',)], ['s',])
>>> df.select("*", sf.lpad(df.s, 6, '#')).show()
+----+-------------+
|   s|lpad(s, 6, #)|
+----+-------------+
|abcd|       ##abcd|
| xyz|       ###xyz|
|  12|       ####12|
+----+-------------+

Example 2: Pad with a bytes column

>>> from pyspark.sql import functions as sf
>>> df = spark.createDataFrame([('abcd',), ('xyz',), ('12',)], ['s',])
>>> df.select("*", sf.lpad(df.s, 6, sf.lit(b"uv"))).show()
+----+-------------------+
|   s|lpad(s, 6, X'7576')|
+----+-------------------+
|abcd|             uvabcd|
| xyz|             uvuxyz|
|  12|             uvuv12|
+----+-------------------+