30
\$\begingroup\$

Introduction

In the wake of the left-pad npm package fallout, 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 , so the submission with the smallest number of bytes wins!

\$\endgroup\$
47
  • 13
    \$\begingroup\$ @m0sa There's still a few issues. Restricting the challenge to javascript is strongly discouraged -- there's no reason other languages can't participate in this. The spec should describe the desired behavior and range of possible allowed inputs without needing to follow a link. It's not clear offhand how the third parameter is being handled. \$\endgroup\$
    – xnor
    Mar 24, 2016 at 11:51
  • 8
    \$\begingroup\$ I am certain that a Javascript-relevant reference can be made for motivation, without having to say "therefore no other languages are allowed to play". If you are particularly interested in seeing the best Javascript entries you could offer a bounty for it, while still leaving the challenge open for other languages. \$\endgroup\$ Mar 24, 2016 at 12:25
  • 6
    \$\begingroup\$ Either single language questions are forbidden or they aren't. If they are forbidden, close this. If they are allowed, let the OP restrict the question as they like. \$\endgroup\$
    – Sklivvz
    Mar 24, 2016 at 12:28
  • 10
    \$\begingroup\$ @Sklivvz (and m0sa) There are rare cases where language-specific challenges make sense, particularly if the challenge requires some very unique feature of a language to make sense or even be a challenge in the first place. That's the main reason those are allowed and why I'd also be opposed to disallowing them completely. That said, for any challenge that does make sense in any language, there's no good reason to restrict it to one language. Otherwise, we'd have "Sort an array in JavaScript", "Sort an array in Ruby", "Sort an array in Python"... and 300 more challenges for no benefit at all. \$\endgroup\$ Mar 24, 2016 at 13:15
  • 8
    \$\begingroup\$ @Sklivvz As trichoplax said, this is a fine motivation for a challenge, but it boils down to a very simple string-processing task that makes just as much sense in any other language. The challenge is not specifically hard, doable or interesting in JavaScript compared to any other language (in particular, someone might not have known about the left-pad package, and still ask this question without the language restriction, and the answers in JavaScript wouldn't have been affected at all, and neither would anyone have thought "why isn't this JS-only?"). \$\endgroup\$ Mar 24, 2016 at 13:34

23 Answers 23

20
\$\begingroup\$

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.

\$\endgroup\$
9
  • 4
    \$\begingroup\$ This is suppose to be javascript only \$\endgroup\$
    – MMM
    Mar 24, 2016 at 12:21
  • 23
    \$\begingroup\$ @MMM Language restrictions in challenges are so universally disliked that I expect it to be summarily ignored. Nobody likes to be told "you can't participate." \$\endgroup\$
    – xnor
    Mar 24, 2016 at 12:23
  • 36
    \$\begingroup\$ @MMM en.wikipedia.org/wiki/Civil_disobedience \$\endgroup\$
    – Doorknob
    Mar 24, 2016 at 12:24
  • 2
    \$\begingroup\$ Stick it to the man! You go Doorknob! Don't let your dreams be dreams! JUST DO IT! \$\endgroup\$
    – Mave
    Mar 24, 2016 at 13:14
  • 5
    \$\begingroup\$ 'Tis a wicked society where the moderators are the one doing civil disobedience! \$\endgroup\$
    – Ven
    Mar 24, 2016 at 13:19
13
\$\begingroup\$

JavaScript (ES6), 43 bytes

f=(s,n,p=" ",r=p)=>(r+=s+="")[n]?s:f(r,n,p)
\$\endgroup\$
11
  • 1
    \$\begingroup\$ you're missing the 3rd parameter \$\endgroup\$
    – m0sa
    Mar 24, 2016 at 11:43
  • \$\begingroup\$ @m0sa Thanks, fixed. \$\endgroup\$
    – Neil
    Mar 24, 2016 at 12:29
  • \$\begingroup\$ It fails the third test, now ;-) \$\endgroup\$
    – Sklivvz
    Mar 24, 2016 at 12:35
  • 1
    \$\begingroup\$ @Sklivvz Ugh, that's what I get for not reading the requirements properly. \$\endgroup\$
    – Neil
    Mar 24, 2016 at 12:41
  • \$\begingroup\$ Instead of p+=s, you can add 2 bytes to make it p+=[s], and it'll work. \$\endgroup\$
    – Aplet123
    Mar 26, 2016 at 20:48
7
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ I think that generally, we don't count the function declaration unless the question specifically asks for a full program rather than a function. \$\endgroup\$
    – Deusovi
    Mar 24, 2016 at 13:44
  • \$\begingroup\$ slice is shorter than substr. \$\endgroup\$ Mar 24, 2016 at 13:46
  • \$\begingroup\$ @Deusovi right. what I mean is that I wouldn't do console.log(f("whatever",10, "*")), but console.log(("*".repeat(10)+"whatever").substr(-10)) \$\endgroup\$
    – Sklivvz
    Mar 24, 2016 at 14:05
7
\$\begingroup\$

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.

\$\endgroup\$
2
  • \$\begingroup\$ This is what I was going to do, except it wasn't an anonymous function. \$\endgroup\$
    – Aplet123
    Mar 28, 2016 at 16:25
  • \$\begingroup\$ @Aplet123 I think by the contest's definition of what's expected this is ok. It was just asking for the function; naming it is irrelevant in this context or at least that's what I would think based on other answers. \$\endgroup\$
    – David
    Mar 28, 2016 at 20:50
5
\$\begingroup\$

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
\$\endgroup\$
9
  • \$\begingroup\$ It's a bit shorter to do (x*b+a)[-b:] or a.rjust(b,x). Actually, str.rjust itself arguably works for the whole thing. \$\endgroup\$
    – xnor
    Mar 24, 2016 at 14:20
  • \$\begingroup\$ @xnor I forgot rjust was a builtin, thank you! \$\endgroup\$
    – cat
    Mar 24, 2016 at 14:26
  • \$\begingroup\$ None of these follow the spec: f(1, 2, 0) === '01'; \$\endgroup\$ Mar 24, 2016 at 16:58
  • \$\begingroup\$ @ValentinLorentz I asked the OP for clarification on languages that don't coerce numbers to strings by default, and haven't gotten an answer. As this question has no formal specification, I'm going to assume the arguments are all strings. \$\endgroup\$
    – cat
    Mar 26, 2016 at 15:38
  • \$\begingroup\$ Now there's a spec, and solution 1 is invalid (tested on Python 2.7.10) \$\endgroup\$ Mar 27, 2016 at 21:19
5
\$\begingroup\$

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.

\$\endgroup\$
1
  • 1
    \$\begingroup\$ All these chars fit into the Jelly codepage (0x672D188330401181FA) \$\endgroup\$ Mar 24, 2016 at 17:14
5
\$\begingroup\$

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.

\$\endgroup\$
4
\$\begingroup\$

Mathematica, 13 bytes

StringPadLeft

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

##2~StringRepeat~(#3-Length@#2)<>#&
\$\endgroup\$
6
  • \$\begingroup\$ May I quietly downvote? \$\endgroup\$
    – edc65
    Mar 27, 2016 at 21:04
  • 2
    \$\begingroup\$ ...Why? Is it because this is just a builtin? The 41byte Python answer #1 (which is no longer valid) was just a wrapper for a builtin. \$\endgroup\$ Mar 27, 2016 at 21:18
  • \$\begingroup\$ It's common practice to disallow built-ins that exactly implement what the challenge asks if that's a concern. (Appeal to authority: Martin)(but common sense, too) \$\endgroup\$
    – edc65
    Mar 27, 2016 at 21:22
  • \$\begingroup\$ @edc65 Related meta post. I'm pretty sure it's allowed, since built-ins are generally allowed by default. It requires creativity and knowledge on the user's part to know the relevant built-in function. \$\endgroup\$
    – mbomb007
    Apr 1, 2016 at 16:17
  • 1
    \$\begingroup\$ @mbomb007 allowed maybe - creative no. I did not flag this answer as invalid but mantain my downvote \$\endgroup\$
    – edc65
    Apr 1, 2016 at 16:51
3
\$\begingroup\$

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"
\$\endgroup\$
2
  • \$\begingroup\$ Does it work for rect 7 cor? \$\endgroup\$ Mar 27, 2016 at 21:12
  • \$\begingroup\$ Yes. lpad("rect", 7, "cor") => "correct" \$\endgroup\$ Mar 27, 2016 at 23:37
3
\$\begingroup\$

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.

\$\endgroup\$
3
  • \$\begingroup\$ Since the question is on hold I'm going to put my answer under the JS answer that's most like mine. 43 bytes (s,n,c=' ')=>(Array(n).join(c)+s).slice(-n) \$\endgroup\$ Mar 25, 2016 at 18:08
  • \$\begingroup\$ Tip: ` for inline code blocks.. \$\endgroup\$ Mar 27, 2016 at 20:51
  • \$\begingroup\$ += returns the value of its left operand, so the second version becomes shorter: (a,n,c=' ')=>(new Array(++n-(a+='').length).join(c)+a) But it becomes longer when you add multichar padding strings. \$\endgroup\$ Mar 27, 2016 at 21:09
3
\$\begingroup\$

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 ³.
\$\endgroup\$
2
  • \$\begingroup\$ padchar (⁵, defaults to 10) shouldn't it default to 20 or 32? \$\endgroup\$
    – cat
    Apr 13, 2016 at 14:23
  • 1
    \$\begingroup\$ Superscript 3 to 9 are constants that are initialized to arguments (if present) or some useful default values. The conditional ? checks if it has its default value 10 and yields a space in that case. \$\endgroup\$
    – Dennis
    Apr 13, 2016 at 14:30
3
\$\begingroup\$

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)
\$\endgroup\$
3
\$\begingroup\$

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.

\$\endgroup\$
2
\$\begingroup\$

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)

\$\endgroup\$
1
  • \$\begingroup\$ You can remove s=str and replace s with str for same byte count. \$\endgroup\$ Mar 24, 2016 at 17:16
1
\$\begingroup\$

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...

\$\endgroup\$
2
  • \$\begingroup\$ Another language with stupid truthys. \$\endgroup\$ Mar 24, 2016 at 17:09
  • \$\begingroup\$ @CatsAreFluffy yeah, Pike is kinda weird, but it has nice string processing utilities. \$\endgroup\$
    – cat
    Mar 24, 2016 at 17:50
1
\$\begingroup\$

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
\$\endgroup\$
5
  • \$\begingroup\$ +1 because answering in the language is helping you refine it :) \$\endgroup\$
    – cat
    Mar 24, 2016 at 19:24
  • \$\begingroup\$ I've edited the format of your header to make it easier to read & easier for userscripts, etc to parse -- roll it back if you disagree. \$\endgroup\$
    – cat
    Mar 24, 2016 at 19:26
  • \$\begingroup\$ Why the downvote? \$\endgroup\$
    – Blue
    Mar 25, 2016 at 10:23
  • 1
    \$\begingroup\$ @muddyfish It seems that every non-Javascript answer here is downvoted. \$\endgroup\$
    – Adnan
    Mar 25, 2016 at 10:36
  • \$\begingroup\$ @AandN thats just not nice... Also why I couldn't see a pattern from the top 6 answers \$\endgroup\$
    – Blue
    Mar 25, 2016 at 10:49
1
\$\begingroup\$

JavaScript ES6, 38 bytes

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

An alternate solution.

\$\endgroup\$
1
\$\begingroup\$

JavaScript (ES6), 34 bytes

I used a recursive solution.

f=(s,l,c=' ')=>s[l-1]?s:f(c+s,l,c)
\$\endgroup\$
0
\$\begingroup\$

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"
\$\endgroup\$
1
  • \$\begingroup\$ You don't need to use that method name... and you can probably make it a lambda, too. (All the other examples do similar) \$\endgroup\$ Apr 13, 2016 at 20:17
0
\$\begingroup\$

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)

\$\endgroup\$
1
  • \$\begingroup\$ This TypeErrors. Can always test Ideone (Java 7, but I get the same exact error in Java 8 on my box) ideone.com/B7gTA5 \$\endgroup\$
    – cat
    Apr 13, 2016 at 14:21
0
\$\begingroup\$

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
\$\endgroup\$
0
\$\begingroup\$

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="")
\$\endgroup\$
-3
\$\begingroup\$

C, 64 bytes

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

Try it here.

\$\endgroup\$
7
  • 2
    \$\begingroup\$ This does not comply with the specification, as it does not default to space when a character is not provided. \$\endgroup\$
    – Doorknob
    Mar 24, 2016 at 15:52
  • \$\begingroup\$ This code doesn't run as given. gcc will let undefined reference to function printf pass and include printf itself, but no such luck for memset, asprintf, and strlen. You need to add the #include<string.h>... etc definitions to make this valid. \$\endgroup\$
    – cat
    Mar 24, 2016 at 17:53
  • \$\begingroup\$ @tac Hmmm...I wrote and tested my answer completely within ideone. It compiles and runs successfully on that platform, though it states that it uses gcc-5.1. I'm not sure if they're using compiler flags or what-have-you behind the scenes that I'm not aware of. I was initially using this as my justification for it not running in your environment, but now I'm not sure... \$\endgroup\$ Mar 24, 2016 at 18:40
  • \$\begingroup\$ well, this is gcc 5.2.1 on Linux, so you might be able to get away with saying Ideone C, 64 bytes but if you're gonna claim it's C, make it compile. :p \$\endgroup\$
    – cat
    Mar 24, 2016 at 20:31
  • \$\begingroup\$ I'm only a beginner at C: Why does f take four parameters, not 3? Are you requiring the address of the string, or...? either way, f should take at most 3 arguments. \$\endgroup\$
    – cat
    Mar 24, 2016 at 20:32

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.