Programming Puzzles & Code Golf Stack Exchange is a question and answer site for programming puzzle enthusiasts and code golfers. It's 100% free, no registration required.

Sign up
Here's how it works:
  1. Anybody can ask a question
  2. Anybody can answer
  3. The best answers are voted up and rise to the top

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!

share|improve this question
11  
@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. – xnor Mar 24 at 11:51
8  
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. – trichoplax Mar 24 at 12:25
6  
@Sklivvz Single language is allowed, though I may venture to say it's the reason the downvotes are pouring in now. We should discuss though banning it in the future, since it's existence seems like a trap. – xnor Mar 24 at 12:33
10  
@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. – Martin Ender Mar 24 at 13:15
6  
@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?"). – Martin Ender Mar 24 at 13:34

21 Answers 21

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.

share|improve this answer
4  
This is suppose to be javascript only – MMM Mar 24 at 12:21
20  
@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." – xnor Mar 24 at 12:23
32  
2  
Stick it to the man! You go Doorknob! Don't let your dreams be dreams! JUST DO IT! – Mave Mar 24 at 13:14
4  
'Tis a wicked society where the moderators are the one doing civil disobedience! – ven Mar 24 at 13:19

JavaScript (ES6), 43 bytes

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

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.

share|improve this answer
    
I think that generally, we don't count the function declaration unless the question specifically asks for a full program rather than a function. – Deusovi Mar 24 at 13:44
    
slice is shorter than substr. – Mama Fun Roll Mar 24 at 13:46
    
@Deusovi right. what I mean is that I wouldn't do console.log(f("whatever",10, "*")), but console.log(("*".repeat(10)+"whatever").substr(-10)) – Sklivvz Mar 24 at 14:05

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
share|improve this answer
    
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. – xnor Mar 24 at 14:20
    
@xnor I forgot rjust was a builtin, thank you! – cat Mar 24 at 14:26
    
None of these follow the spec: f(1, 2, 0) === '01'; – Valentin Lorentz Mar 24 at 16:58
    
@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. – cat Mar 26 at 15:38
    
Now there's a spec, and solution 1 is invalid (tested on Python 2.7.10) – CalculatorFeline Mar 27 at 21:19

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.

share|improve this answer

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.

share|improve this answer
1  
All these chars fit into the Jelly codepage (0x672D188330401181FA) – CalculatorFeline Mar 24 at 17:14

Mathematica, 13 bytes

StringPadLeft

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

##2~StringRepeat~(#3-Length@#2)<>#&
share|improve this answer
    
May I quietly downvote? – edc65 Mar 27 at 21:04
2  
...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. – CalculatorFeline Mar 27 at 21:18
    
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) – edc65 Mar 27 at 21:22
    
@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. – mbomb007 Apr 1 at 16:17
    
@mbomb007 allowed maybe - creative no. I did not flag this answer as invalid but mantain my downvote – edc65 Apr 1 at 16:51

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.

share|improve this answer
    
This is what I was going to do, except it wasn't an anonymous function. – Aplet123 Mar 28 at 16:25
    
@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. – David Mar 28 at 20:50
    
+1 This is literally my exact code! Good Job! – SpeedyNinja Apr 13 at 21:18

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"
share|improve this answer
    
Does it work for rect 7 cor? – CalculatorFeline Mar 27 at 21:12
    
Yes. lpad("rect", 7, "cor") => "correct" – Fengyang Wang Mar 27 at 23:37

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.

share|improve this answer
    
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) – Charlie Wynn Mar 25 at 18:08
    
Tip: ` for inline code blocks.. – CalculatorFeline Mar 27 at 20:51
    
+= 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. – CalculatorFeline Mar 27 at 21:09

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.

share|improve this 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)

share|improve this answer
    
You can remove s=str and replace s with str for same byte count. – CalculatorFeline Mar 24 at 17:16
    
Edited, thanks. – Valentin Lorentz Mar 24 at 17:18

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 ³.
share|improve this answer
    
padchar (⁵, defaults to 10) shouldn't it default to 20 or 32? – cat Apr 13 at 14:23
1  
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. – Dennis Apr 13 at 14:30

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

share|improve this answer
    
Another language with stupid truthys. – CalculatorFeline Mar 24 at 17:09
    
@CatsAreFluffy yeah, Pike is kinda weird, but it has nice string processing utilities. – cat Mar 24 at 17:50

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
share|improve this answer
    
+1 because answering in the language is helping you refine it :) – cat Mar 24 at 19:24
    
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. – cat Mar 24 at 19:26
    
Why the downvote? – muddyfish Mar 25 at 10:23
1  
@muddyfish It seems that every non-Javascript answer here is downvoted. – Adnan Mar 25 at 10:36
    
@AandN thats just not nice... Also why I couldn't see a pattern from the top 6 answers – muddyfish Mar 25 at 10:49

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)

share|improve this answer
    
This TypeErrors. Can always test Ideone (Java 7, but I get the same exact error in Java 8 on my box) ideone.com/B7gTA5 – cat Apr 13 at 14:21

JavaScript ES6, 38 bytes

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

An alternate solution.

share|improve this 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)
share|improve this 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"
share|improve this answer
    
You don't need to use that method name... and you can probably make it a lambda, too. (All the other examples do similar) – Not that Charles Apr 13 at 20:17

PHP, 54 bytes

Uses Windows-1252 encoding.

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

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

php -d error_reporting=30709 -r '$f = function(&$s,$l,$p=~ß){for(;strlen($s)<$l;)$s=$p.$s;}; $s="foo";$f($s,5);echo"$s\n";'
share|improve this answer

C, 64 bytes

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

Try it here.

share|improve this answer
1  
This does not comply with the specification, as it does not default to space when a character is not provided. – Doorknob Mar 24 at 15:52
    
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. – cat Mar 24 at 17:53
    
@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... – Cole Cameron Mar 24 at 18:40
    
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 – cat Mar 24 at 20:31
    
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. – cat Mar 24 at 20:32

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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