[Question]
  [
### Introduction
In the wake of the [left-pad npm package](https://www.npmjs.com/package/left-pad) [fallout](https://www.reddit.com/r/programming/comments/4bjss2/an_11_line_npm_package_called_leftpad_with_only/), let's have a code golf for implementing left-pad.
The *left-pad* function consists of 2 default arguments and 1 additional argument, in the form **string**, **length**, (**padchar**). If the padchar is not given, this is **standardized** to a *space character*. Let's take an example with two arguments:
```
left_pad("abc", 6)
```
First, we observe the length of the string, which is **3**. After this, we need to pad this string in the left until the length of the full string has reached the length given in the function. In this case **6**. Since the padchar is *not given*, we need to pad this with spaces:
```
   abc
```
This is a string with 3 spaces and the initial string, resulting into a string with length 6. Here is an example with the padchar given:
```
left_pad("abc", 6, "-")
```
We just do the same as the example above, but replace the spaces with the padchar. In this case, the hyphen:
```
---abc
```
### The Task
Given the **string**, **length**, and *maybe* the additional argument **padchar**, output the left-padded string. You can assume that the length number is equal or greater than the length of the string. The padchar will always consist of 1 character.
### Test cases
```
left_pad("string", length, ("padchar")) === "left-padded string"
left_pad("foo", 5) === "  foo"
left_pad("foobar", 6) === "foobar"
left_pad("1", 2, "0") === "01"
left_pad("1", 2, "-") === "-1"
```
This is [code-golf](/questions/tagged/code-golf "show questions tagged 'code-golf'"), so the submission with the smallest number of bytes wins!
  
[Answer]
## Pyth, ~~13~~ 11 bytes
```
+*.xwd-Qlzz
```
[Try it here](http://pyth.herokuapp.com/?code=%2B%2a.xwd-Qlzz&input=foo%0A5&debug=0).
Takes input from STDIN as the string on the first line, length on the second line, and padding char optionally on a third line.
[Answer]
## JavaScript (ES6), 43 bytes
```
f=(s,n,p=" ",r=p)=>(r+=s+="")[n]?s:f(r,n,p)
```
[Answer]
# Javascript ES6, 35 bytes
```
(s,l,c=' ')=>c.repeat(l-s.length)+s
```
[Try it.](https://jsfiddle.net/ff41ht4c/2/) I believe this is the shortest possible implimentation currently possible in Javascript.
[Answer]
# 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.
[Answer]
# Python 3, ~~33~~ ~~31~~ 29 bytes
```
lambda a,b,x=" ":a.rjust(b,x)
```
~~Fairly straightforward.~~ Thanks to [@xnor](https://codegolf.stackexchange.com/users/20260/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
```
[Answer]
# [05AB1E](http://github.com/Adriandmen/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](http://05ab1e.tryitonline.net/#code=Zy3DsMKzMEDDl8K5wqs&input=Zm9vCjUKLQ).
[Answer]
# Mathematica, 13 bytes
```
StringPadLeft
```
Builtin-only answer #3 (first was `Range`, second was `Surd`)
Or less builtin: (35 bytes)
```
##2~StringRepeat~(#3-Length@#2)<>#&
```
[Answer]
## 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.
[Answer]
# 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)
```
[Answer]
# 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"
```
[Answer]
# 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. 
[Answer]
# 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*.
[Answer]
# 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)
[Answer]
# [Jelly](https://github.com/DennisMitchell/jelly), 12 [bytes](https://github.com/DennisMitchell/jelly/wiki/Code-page)
```
L⁴_ẋ@⁵⁵⁶<?¤³
```
*So* many variable references. Wasn't Jelly supposed to be a *tacit* language?
[Try it online!](http://jelly.tryitonline.net/#code=TOKBtF_huotA4oG14oG14oG2PD_CpMKz&input=&args=ImFiYyI+Ng+Ii0i)
### 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 ³.
```
[Answer]
# JavaScript (ES6), 34 bytes
I used a recursive solution.
```
f=(s,l,c=' ')=>s[l-1]?s:f(c+s,l,c)
```
[Answer]
# [Lua](https://www.lua.org/), 39 38 bytes
```
s,n,c=...print((c or" "):rep(n-#s)..s)
```
[Try it online!](https://tio.run/##yylN/P@/WCdPJ9lWT0@voCgzr0RDI1khv0hJQUnTqii1QCNPV7lYU0@vWPP///@JScn/zf7rAgA "Lua – Try It Online")
Thanks to c-- for saving a byte.
[Answer]
# [Japt](https://github.com/ETHproductions/japt), 5 [bytes](https://en.wikipedia.org/wiki/ISO/IEC_8859-1)
```
ùVWªS
```
[Try it](https://petershaggynoble.github.io/Japt-Interpreter/?v=1.4.6&code=%2bVZXqlM&input=ImZvbyIgNiAiLSI)
```
ù      # 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.
[Answer]
# [C (gcc)](https://gcc.gnu.org/), ~~91~~ 86 bytes
Takes 2 or 3 arguments on the command line. Also uses the rare ["-->" operator](https://stackoverflow.com/questions/1642028/what-is-the-operator-in-c-c)!
*-5 bytes from [ceilingcat](https://codegolf.stackexchange.com/users/52904/ceilingcat) and [c--](https://codegolf.stackexchange.com/users/112488/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!](https://tio.run/##HcrBDoIwDIDh12kHvcDBhEZ9EMNhaVCW1M2M0Qvx2Svx@n@/0EvEXfkdUwbpDVNuIRgfz1JBr7GVBNZ1j2FGVqLb1qouGYIh42dvssYKQuM92LlM44B81u3vX3dfF9XiF6cf "C (gcc) – Try It Online")
[Answer]
# Powershell, ~~87~~ ~~67~~  ~~incorrect counted 54~~, 46 Bytes
```
function f($s,$l,$c=' '){$c*($l-$s.length)+$s}
```
[Try it online!](https://tio.run/##K8gvTy0qzkjNyfn/P600L7kkMz9PIU1DpVhHJUdHJdlWXUFds1olWUtDJUdXpVgvJzUvvSRDU1uluPZ/moJSWn6@koIpF4SVlFikpGAG4hgqKRgpKBkoIdi6Sv8B "PowerShell – Try It Online")
[Answer]
# [Pike](http://pike.lysator.liu.se), 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...
[Answer]
## [Pyke](https://github.com/muddyfish/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
```
[Answer]
# JavaScript ES6, 38 bytes
```
(s,l,c=" ")=>(c.repeat(l)+s).slice(-l)
```
An alternate solution.
[Answer]
# [Arturo](https://arturo-lang.io), 34 bytes
```
$=>[++repeat ??attr""" "&-size<=&]
```
[Try it](http://arturo-lang.io/playground?ElsxF0)
Arturo has `pad` but here's a non-builtin.
[Answer]
# [Vyxal](https://github.com/Vyxal/Vyxal), 8 bytes
```
□ðJ3Ẏ÷ø↳
```
[Try it Online!](https://vyxal.pythonanywhere.com/?v=1#WyJ+IiwiIiwi4pahw7BKM+G6jsO3w7jihrMiLCIiLCIhbGVmdF9wYWRcXCgoLiopXFwpID09PSBcIiguKilcIlxubGVmdF9wYWQoXCJmb29cIiwgNSkgPT09IFwiICBmb29cIlxubGVmdF9wYWQoXCJmb29iYXJcIiwgNikgPT09IFwiZm9vYmFyXCJcbmxlZnRfcGFkKFwiMVwiLCAyLCBcIjBcIikgPT09IFwiMDFcIlxubGVmdF9wYWQoXCIxXCIsIDIsIFwiLVwiKSA9PT0gXCItMVwiIl0=)
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. 
```
[Answer]
# 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"
```
[Answer]
# 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)
[Answer]
# 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
* Saved 6 bytes by using `str_pad` instead of a loop. Leaving the old one for reference, as builtins are frowned upon
[Answer]
## 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="")
```
[Answer]
# [brainfuck](https://github.com/TryItOnline/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!](https://tio.run/##VY4xCsNQDEP3XMVxtm5CFzEe0kKgFBoo9Pw/@i79Tb1ZerJ8fa335/a@PVqbfUzYGAQSRgbzBGTJwDmDcPxyFOI0JMmvJqBQebXY/02VuG66Eln4CEImhM8ht0N6KKvgE7EeQf9I0lKdchZma9u@T5fpAA "brainfuck – Try It Online")
[Answer]
# [Go](https://go.dev), 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!](https://ato.pxeger.com/run?1=fY5BisIwFIb3OUV4ICSYFisoIugZZLYzgpmQlGD7mqbpbEpPMEeYTRE8hEfxNtNa3amrH_7v8b7_75QW3cVJdZSpprm0SGzuCh9iMHmAcx1MtLrio6uCt5hWQEyNimYMqcUgVBzHI-FjNKVw6436nO0FUCDW0EwjU3ybNK6vk31LvA61R_qhnZaBOYHRcFJyPi3bu_X3Jhk2MU4bsus_B8PgMPk5fCGIXr8QYIoCOH8Glzf4Lf0LPheQgIDZW0whGvh9UteN-Q8)
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](https://go.dev), 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!](https://ato.pxeger.com/run?1=m70oPX_BzoLE5OzE9FSF3MTMPK7M3IL8ohI9pbTcEqWlpSVpuhY3fWBixSVFmXnpxUpcaaV5yQo5GsU6yQoQMZ08hcy8Ek0Ip7ootaS0KE8hKLUgNbFEI1knTzcnNU-jWFNTu7gWauYssBEgGzU0Faq5AoD6StI0lBJUyxJi8pR0gIYrpeXnAxlKCkDCVFMTl5KkxCKYKjMcqgxBCgyAhBE-BbpQBVAXLlgAoQE)
]