Menu

Sign in to track your progress and unlock all features.

Theme style

Log in

Full lesson preview

Trim and pad a string

Trim a string if it's too long and center-pad it if it's too short, using a specified pad character.

Python practice14 minString PatternsIntermediateLast updated March 18, 2026

Problem statement

Create a function that takes an input string s, an integer length, and an optional pad character pad_char (default is space). The function should: - If length is less than or equal to zero, return the empty string. - If s is longer than length, truncate s to exactly length characters by keeping the first length characters (drop the rest). - If s is shorter than length, pad it on both sides to reach the target length. If an odd number of padding characters is needed, put the extra pad on the right. - Assume pad_char is a single character. Return the resulting string (not printed).

Task

Implement a function that enforces a target length by trimming or center-padding a string deterministically.

Examples

Pad with asterisks

Input

s='hello', length=10, pad_char='*'

Output

**hello***

Original length 5, target 10 => need 5 pads; distribute 2 on left and 3 on right.

Input format

Function inputs: string s, integer length, optional single-character pad_char.

Output format

A single string of exactly the requested length (or empty string if length <= 0).

Constraints

length is an integer (can be zero or positive). pad_char is a single character. Do not use external libraries.

Samples

Sample 1

Input

s='longstring', length=4

Output

long

Truncate to the first 4 characters.