102

I'm sure this is covered in plenty of places, but I don't know the exact name of the action I'm trying to do so I can't really look it up. I've been reading an official Python book for 30 minutes trying to find out how to do this.

Problem: I need to put a string in a certain length "field".

For example, if the name field was 15 characters long, and my name was John, I would get "John" followed by 11 spaces to create the 15 character field.

I need this to work for any string put in for the variable "name".

I know it will likely be some form of formatting, but I can't find the exact way to do this. Help would be appreciated.

Trenton McKinney
  • 56,955
  • 33
  • 144
  • 158
user2977230
  • 8,897
  • 5
  • 14
  • 9

10 Answers10

155

This is super simple with format:

>>> a = "John"
>>> "{:<15}".format(a)
'John           '
Games Brainiac
  • 80,178
  • 33
  • 141
  • 199
  • 1
    @GamesBrainiac `format` is quite overkill for this simple case, but once understood, it's so powerful that it deserves the initial learning cost! +1 then. – Joël Dec 01 '13 at 09:38
  • 12
    If the text is longer than 15 characters, `format` won't truncate it. To do that write: `'{:<15}'.format(a[:15])` – ChaimG Jun 15 '16 at 16:00
  • 14
    From Python version 3.6 you can use f-strings instead of string.format() `f"{a:<15}"` – alec_djinn Apr 18 '18 at 15:32
  • how can this be used if instead of `format` I want to print like `"Hello %s!" % name `? – hipoglucido Jul 13 '18 at 13:05
  • 1
    Nice! This adds spaces to the right of the string. Can this be used to pad a string from the left too, or to pad it with something else than spaces? For example, if I want to pad an non-negative integer with zeros from the left to a specific length? – HelloGoodbye Oct 12 '20 at 16:18
  • 5
    I found the answer to my own question [here](https://www.python.org/dev/peps/pep-3101/#standard-format-specifiers); you simply switch `<` to `>` if you want right alignment, and you enter the fill character before the `<` or `>`. For example, `'{:0>5}'.format(167)` produces the string `'00167'`. If you have signed numbers, you can replace `>` with `=`, i.e., '{:0=5}'.format(-167), to get the fill character between the sign and the number, i.e., `'-0167'` – HelloGoodbye Oct 12 '20 at 20:47
117

You can use the ljust method on strings.

>>> name = 'John'
>>> name.ljust(15)
'John           '

Note that if the name is longer than 15 characters, ljust won't truncate it. If you want to end up with exactly 15 characters, you can slice the resulting string:

>>> name.ljust(15)[:15]
Ismail Badawi
  • 36,054
  • 7
  • 85
  • 97
  • 2
    I did not know about this, but hey, thats cool too. I personally prefer `format` for all string operations :P +1 – Games Brainiac Dec 01 '13 at 06:21
  • This answer was also very helpful and I appreciate it very much, thank you. I'm sure it will be useful in the future. – user2977230 Dec 01 '13 at 06:24
  • Easier to understand, hence this seems more preferable – PlanetUnknown Jul 29 '16 at 21:00
  • @GamesBrainiac "I personally prefer format for all string operations" _Ye gods_, why kneecap yourself like that? `a, b = "Hello ", "world!"; %timeit "{}{}".format(a, b)` → 1.17 µs. `%timeit a+b` → 413 ns. [2.833×](https://www.wolframalpha.com/input/?i=413+ns+vs+1.17+µs) slower, and as the previous comment mentions, [_readability_](https://www.python.org/dev/peps/pep-0020/#the-zen-of-python)! – amcgregor Apr 15 '20 at 17:58
  • @amcgregor Speed isn't everything. Sometimes, you want something that has more baked in flexibility, which `.format()` provides. – Games Brainiac Apr 15 '20 at 21:31
  • @GamesBrainiac Do you perform _every_ search and replace in a string with a regular expression—instead of `.replace()`? Every substring inclusion match with one—instead of `x in y`? One could even go so far as to use regular expressions exclusively for all range slicing operations. Ad absurdum to highlight that the most general tool is rarely the most optimal, in significant ways that can not be easily hand-waved away with "flexibility is nice". Wilfully choosing something almost three times slower, in my last example, for ultimately cosmetic reasons seems… fantastically un-sound. – amcgregor Aug 14 '20 at 06:22
31

If you have python version 3.6 or higher you can use f strings

>>> string = "John"
>>> f"{string:<15}"
'John           '

Or if you'd like it to the left

>>> f"{string:>15}"
'          John'

Centered

>>> f"{string:^15}"
'     John      '

For more variations, feel free to check out the docs: https://docs.python.org/3/library/string.html#format-string-syntax

Justin Furuness
  • 685
  • 8
  • 21
  • 2
    What's especially cool is that you can also easily insert lengths you calculated before: `f"{string:<{calculated_length}}"`! – cherrywoods Jan 06 '22 at 13:28
13

You can use rjust and ljust functions to add specific characters before or after a string to reach a specific length. The first parameter those methods is the total character number after transforming the string.

Right justified (add to the left)

numStr = '69' 
numStr = numStr.rjust(5, '*')

The result is ***69

Left justified (add to the right)

And for the left:

numStr = '69' 
numStr = numStr.ljust(3, '#')

The result will be 69#

Fill with Leading Zeros

Also to add zeros you can simply use:

numstr.zfill(8)

Which gives you 00000069 as the result.

hc_dev
  • 8,389
  • 1
  • 26
  • 38
Matin Ashtiani
  • 758
  • 9
  • 11
0
string = ""
name = raw_input() #The value at the field
length = input() #the length of the field
string += name
string += " "*(length-len(name)) # Add extra spaces

This will add the number of spaces needed, provided the field has length >= the length of the name provided

Aswin Murugesh
  • 10,831
  • 10
  • 40
  • 69
  • Similar performance comment as I've added to several other suggestions here: you're constructing multiple copies of the strings involved. The input string, a calculated (un-intern-able) variable length string, then the final resulting padded string. Instead of using the O(1) [tool provided for the job](https://stackoverflow.com/a/20309306/211827). – amcgregor Apr 15 '20 at 19:08
0
name = "John" // your variable
result = (name+"               ")[:15] # this adds 15 spaces to the "name"
                                       # but cuts it at 15 characters
0

I know this is a bit of an old question, but I've ended up making my own little class for it.

Might be useful to someone so I'll stick it up. I used a class variable, which is inherently persistent, to ensure sufficient whitespace was added to clear any old lines. See below:

2021-03-02 update: Improved a bit - when working through a large codebase, you know whether the line you are writing is one you care about or not, but you don't know what was previously written to the console and whether you want to retain it.

This update takes care of that, a class variable you update when writing to the console keeps track of whether the line you are currently writing is one you want to keep, or allow overwriting later on.

class consolePrinter():
'''
Class to write to the console

Objective is to make it easy to write to console, with user able to 
overwrite previous line (or not)
'''
# -------------------------------------------------------------------------    
#Class variables
stringLen = 0    
overwriteLine = False
# -------------------------------------------------------------------------    
    
# -------------------------------------------------------------------------
def writeline(stringIn, overwriteThisLine=False):
    import sys
    #Get length of stringIn and update stringLen if needed
    if len(stringIn) > consolePrinter.stringLen:
        consolePrinter.stringLen = len(stringIn)+1
    
    ctrlString = "{:<"+str(consolePrinter.stringLen)+"}"

    prevOverwriteLine = consolePrinter.overwriteLine
    if prevOverwriteLine:
        #Previous line entry can be overwritten, so do so
        sys.stdout.write("\r" + ctrlString.format(stringIn))
    else:
        #Previous line entry cannot be overwritten, take a new line
        sys.stdout.write("\n" + stringIn)
    sys.stdout.flush()
    
    #Update the class variable for prevOverwriteLine
    consolePrinter.overwriteLine = overwriteThisLine

    return

Which then is called via:

consolePrinter.writeline("text here", True) 

If you want this line to be overwriteable

consolePrinter.writeline("text here",False)

if you don't.

Note, for it to work right, all messages pushed to the console would need to be through consolePrinter.writeline.

Amiga500
  • 1,258
  • 1
  • 6
  • 11
0

I generally recommend the f-string/format version, but sometimes you have a tuple, need, or want to use printf-style instead. I did this time and decided to use this:

>>> res = (1280, 720)
>>> '%04sx%04s' % res
'1280x 720'

Thought it was a touch more readable than the format version:

>>> f'{res[0]:>4}x{res[1]:>4}'
Gringo Suave
  • 29,931
  • 6
  • 88
  • 75
-1

First check to see if the string's length needs to be shortened, then add spaces until it is as long as the field length.

fieldLength = 15
string1 = string1[0:15] # If it needs to be shortened, shorten it
while len(string1) < fieldLength:
    rand += " "
Matt
  • 437
  • 3
  • 10
-1

Just whipped this up for my problem, it just adds a space until the length of string is more than the min_length you give it.

def format_string(str, min_length):
    while len(str) < min_length:
        str += " "
    return str
dragon40226
  • 257
  • 1
  • 4
  • 11
  • 1
    Strings are not arrays in Python, they are immutable objects. Each appending of a space will create a brand new string that is the previous string, extended by one space. However many times it would be required to reach the target length. This is a **highly** sub-optimal solution vs. use of the actual method provided to do so, [also given as an answer](https://stackoverflow.com/a/20309306/211827) which only creates a new Python string object once. – amcgregor Apr 15 '20 at 17:50