g | x | w | all
Bytes Lang Time Link
049AWK241205T184410Zxrs
041Perl 5240528T015519ZXcali
043Powershell230429T162050Zspookyco
110Go230501T132358Zbigyihsu
212brainfuck230501T034345ZATaco
086C gcc230429T164830Zevanstar
005Japt230429T235918Znoodle p
008Vyxal230429T222324Zlyxal
034Arturo230429T215849Zchunes
038Lua230429T185105Zbluswimm
034JavaScript ES6161011T105455ZHuntro
050R161011T100851ZBillywob
048PHP160526T084714Zaross
057Bash160331T223015Zphilcolb
016JavaScript ES7160526T013940ZDowngoat
038JavaScript ES6160424T011549ZConor O&
088Java 8160403T010745Zhyperneu
042Ruby160401T213245Zjose_cas
012Jelly160330T055500ZDennis
035Javascript ES6160328T030335ZDavid
070JavaScript ES5160324T161727Zrjmunro
013Mathematica160324T163743ZCalculat
043JavaScript ES6160324T105747ZNeil
064C160324T154542ZCole Cam
012Pyke160324T174128ZBlue
055Javascript ES6160324T180947Zpllee
004Julia160324T190439ZFengyang
041Python160324T170344ZValentin
067Pike160324T142510Zcat
00905AB1E160324T150533ZAdnan
029Python 3160324T140923Zcat
011Pyth160324T120138ZDoorknob
044JavaScript ES6160324T104419ZSklivvz

AWK, 49 bytes

$0=gensub(/ /,$3?$3:" ","g",sprintf("%*s",$2,$1))

Attempt This Online!

$0=                   # set ouput
gensub(/ /,           # sub spaces for $3
$3?$3:" ","g",        # or spaces if no $3
sprintf("%*s",$2,$1)) # pretty print 

Perl 5, 41 bytes

sub{(@_>1?pop:$")x((pop)-length"@_").pop}

Try it online!

Powershell, 87 67 incorrect counted 54, 46 43 Bytes

$f={param($s,$l,$c='')$c*($l-$s.length)+$s}

Try it online!

Go, 110 bytes

import."strings"
func l(n int,c...string)string{q,p:=c[0]," "
if len(c)>1{p=c[1]}
return Repeat(p,n-len(q))+q}

Attempt This Online!

Uses Go's variadic arguments feature to have an optional argument. Expects at minimum 1 string passed to the function (the string to be padded); the first string after that is the padding character.

A solution were all arguments are explicit is significantly shorter:

Go, 76 bytes, no variadic arguments

import."strings"
func l(s,c string,n int)string{return Repeat(c,n-len(s))+s}

Attempt This Online!

brainfuck, 212 bytes

,----------[++++++++++<[<]<+>>[>],----------]<[<]<<<,----------[<[-<++++++++++>]<[->+<]>>>++++++++[-<----->]<++[-<+>],----------]>>[-<<<->>>]++++[>++++++++<-]><<+>,[<->[-<<+>>]]<[->>[-<<<+>>>]<<]<<[->.<]>>>>>[.>]

Explained

,----------[      While it isn't a newline
    ++++++++++        Restore the character
    <[<]<+>>[>]       Increment the counter behind the array and return
,----------]      Read and repeat
<[<]<<<           navigate behind the length
,----------[                   While it isn't a newline
    <[-<++++++++++>]<[->+<]>>      x10 the stored number
    >++++++++[-<----->]<++             sub 39
    [-<+>]                         Copy into stored
,----------]                   Read and repeat
>>[-<<<->>>]        Subtract the counter from the target
++++[>++++++++<-]>  Prepare a space
<<+>,[<->[-<<+>>]]  If the next byte isnt eof then we copy it left two and zero the test byte
<[->>[-<<<+>>>]<<]  If the text bit is still high copy space in there instead
<<[->.<]            While the counter is positive write the pad char
>>>>>[.>]           Write the rest of the string

Arguments separated by linefeeds. If no pad char is present, a linefeed after the length must still be included.

Try it online!

C (gcc), 91 86 bytes

Takes 2 or 3 arguments on the command line. Also uses the rare "-->" operator!

-5 bytes from ceilingcat and c--

l;main(c,v)int**v;{for(l=atoi(v++[2]);l-->strlen(*v);)putchar(c-3?*v[2]:32);puts(*v);}

Try it online!

Japt, 5 bytes

ùVWªS

Try it

ù      # left-pad the input string with:
 V     #   second input (length)
  WªS  #   third input, or space if not specified

Or, for 1 byte:

ù

But this isn't a full program, so I don't think it counts. It can be called AùBC where A is the string, B is the length, and C is (optionally) the padding character.

Vyxal, 8 bytes

□ðJ3Ẏ÷ø↳

Try it Online!

Link is to test suite. Somehow, vyncode also gives 8 bytes.

Explained

□ðJ3Ẏ÷ø↳
□ðJ      # append a space to all input arguments
   3Ẏ     # take the first 3 items of that
     ÷    # dump everything to the stack
      ø↳  # call the built-in left pad function. 

Arturo, 34 bytes

$=>[++repeat ??attr""" "&-size<=&]

Try it

Arturo has pad but here's a non-builtin.

Lua, 39 38 bytes

s,n,c=...print((c or" "):rep(n-#s)..s)

Try it online!

Thanks to c-- for saving a byte.

JavaScript (ES6), 34 bytes

I used a recursive solution.

f=(s,l,c=' ')=>s[l-1]?s:f(c+s,l,c)

R, 50 bytes

Late to the party again but here it goes:

function(s,n,p=" ")cat(rep(p,n-nchar(s)),s,sep="")

This simply prints the output to stdout but does not actually return the padded string (wasn't sure if this is a requirement for the challenge). If this is needed, the solution is slightly longer at 61 bytes:

function(s,n,p=" ")paste0(c(rep(p,n-nchar(s)),s),collapse="")

PHP, 54 48 bytes

Uses Windows-1252 encoding.

function(&$s,$l,$p=~ß){$s=str_pad($s,$l,$p,0);};

Run like this (-d added for easthetics only):

php -r '$f = function(&$s,$l,$p=~ß){$s=str_pad($s,$l,$p,0);}; $s="foo";$f($s,5);echo"$s\n";' 2>/dev/null

Old version (without the builtin):

function(&$s,$l,$p=~ß){for(;strlen($s)<$l;)$s=$p.$s;};

Tweaks

Bash, 57 Bytes

Parameters: string width padchar

printf -vX %$2s;Y="${X// /${3- }}$1";echo -n "${Y:${#1}}"

Make a string of width spaces.

Convert each space character into padchar.

Write padding then string.

JavaScript ES7, 16 bytes

''.padStart.bind

built-ins ftw! Only works on Firefox 48 and above. Valid as this feature was added March 12.

This takes input like:

(''.padStart.bind)(arg1)(arg2,arg3)

JavaScript ES6, 38 bytes

(s,l,c=" ")=>(c.repeat(l)+s).slice(-l)

An alternate solution.

Java 8, 86 88 bytes

This is a function. The third argument is a varargs to allow the optional pad char (defaults to ' ')

String p(String s,int l,char...p){return s.length()<l?p((p.length>0?p[0]:' ')+s,l,p):s;}

Recursion! +2 bytes (added brackets because of incompatible type error)

Ruby, 42 bytes

def left_pad(s,t,p=" ");p*(t-s.size)+s;end

Parameters: string, size, padchar.

Test suite below; should print all "true"s, just put everything in the same file.

puts left_pad("foo", 5) == "  foo"
puts left_pad("foobar", 6) == "foobar"
puts left_pad("1", 2, "0") == "01"
puts left_pad("1", 2, "-") == "-1"

Jelly, 12 bytes

L⁴_ẋ@⁵⁵⁶<?¤³

So many variable references. Wasn't Jelly supposed to be a tacit language?

Try it online!

How it works

L⁴_ẋ@⁵⁵⁶<?¤³  Main link
              Arguments: string (³), length (⁴), padchar (⁵, defaults to 10)

L             Compute the length of ³.
 ⁴_           Subtract the length from ⁴.
          ¤   Combine the two links to the left into a niladic chain:
     ⁵          Yield ⁵.
      ⁵⁶<?      Yield ⁵ if ⁵ < ⁵, else ⁶.
              Comparing a number with itself gives 0 (falsy), but comparing a
              string / character list with itself gives [0] (truthy).
   ẋ@         Repeat the result to the right as many times as specified in the
              result to the left.
           ³  Print the previous return value and return ³.

Javascript ES6, 35 bytes

(s,l,c=' ')=>c.repeat(l-s.length)+s

Try it. I believe this is the shortest possible implimentation currently possible in Javascript.

JavaScript (ES5), 70 bytes

Using recursion...

function f(s,c,p,u){return(s+'').length<c?f((p==u?' ':p+'')+s,c,p):s}

My initial go was only 57 bytes:

function f(s,c,p){return s.length<c?f((p||" ")+s,c,p):s}

But only passed the first 2 tests:

> f('foo', 5) === '  foo';
true
> f('foobar', 6) === 'foobar';
true
> f(1, 2, 0) === '01';
false
> f(1, 2, '-') === '-1';
false

I still like the shorter one, because in practise, passing numbers to a string manipulation function isn't a feature I would need.

Mathematica, 13 bytes

StringPadLeft

Builtin-only answer #3 (first was Range, second was Surd) Or less builtin: (35 bytes)

##2~StringRepeat~(#3-Length@#2)<>#&

JavaScript (ES6), 43 bytes

f=(s,n,p=" ",r=p)=>(r+=s+="")[n]?s:f(r,n,p)

C, 64 bytes

f(s,n,c,p){return memset(p,c,asprintf(&p,"%*s",n,s)-strlen(s));}

Try it here.

Pyke, 12 bytes (noncompeting)

added input node, bugfix on len node, change default results on assign node after the challenge was posted.

\ =zzjl-z*j+

Explanation:

\ =z         - assign default input for `z` to be " " (Will still prompt but no input will return a space instead)
    zj       -     j = input()
      l      -    len(j)
       -     -   eval_or_not_input() - ^
        z*   -  ^*input()
          j+ - ^+j

Javascript (ES6), 55 bytes

(a,n,c=' ',s=a+'')=>(new Array(++n-s.length).join(c)+s)

Create an empty array of values and join version.

(a,n,c=' ')=>{a+=''; return new Array(++n-a.length).join(c)+a}

Is more readable but the return adds a few more characters.

Julia, 4 bytes

lpad

Passes all the test cases:

julia> lpad("foo", 5)
"  foo"

julia> lpad("foobar", 6)
"foobar"

julia> lpad(1, 2, 0)
"01"

julia> lpad(1, 2, '-')
"-1"

Python, 41 bytes

lambda a,b,x=' ':str(a).rjust(b,str(x))

Without the builtin rjust, 43 bytes:

lambda a,b,x=' ':str(x)*int(b/2%3)+str(a)

(not what one expects it to do, but it passes the test suite)

Pike, 67 bytes

mixed n(mixed a,int b,mixed x){return x!=""?x:" "*(b-strlen(a))+a;}

sigh. The empty string "" evaluates to true. Why!?

mixed mixed mixed mixed mixed Pike soup...

05AB1E, 11 9 bytes

Code:

g-ð³0@×¹«

Explanation:

g          # Implicit first input, take the length.
 -         # Substract the length with the second input.
  ð³       # Push a space and if the third input exists, also the third input.         
    0@     # Reposition the first element of the stack to the top (zero-indexed).
      ×    # Multiply the character with the difference in length.
       ¹«  # Concatenate the first input to the string.

Uses CP-1252 encoding. Try it online.

Python 3, 33 31 29 bytes

lambda a,b,x=" ":a.rjust(b,x)

Fairly straightforward. Thanks to @xnor for reminding me str.rjust is a thing. :P

For the same length (also thanks to xnor):

lambda a,b,x=" ":(x*b+a)[-b:]

Previous solution:

lambda a,b,x=" ":x*(b-len(a))+a

Pyth, 13 11 bytes

+*.xwd-Qlzz

Try it here.

Takes input from STDIN as the string on the first line, length on the second line, and padding char optionally on a third line.

JavaScript (ES6), 37 43 44 bytes

(a,n,c=' ')=>((c+'').repeat(n)+a).substr(-n)

Test:

> f=(a,n,c)=>((c?c:" ").repeat(n)+a).substr(-n)
< function (a,n,c)=>((c?c:" ").repeat(n)+a).substr(-n)
> f('foo', 5) === '  foo';
< true
> f('foobar', 6) === 'foobar';
< true
> f(1, 2, 0) === '01';
< true
> f(1, 2, '-') === '-1';
< true

Not sure if you want to count the function declaration, I'd inline this.