Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pad a string to a fixed length with spaces in Python?

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.

like image 509
user2977230 Avatar asked Dec 01 '13 06:12

user2977230


People also ask

How do you add spaces to a string in Python?

We add space in string in python by using rjust(), ljust(), center() method. To add space between variables in python we can use print() and list the variables separate them by using a comma or by using the format() function.

How do you trim a string to a specific length in Python?

Use syntax string[x:y] to slice a string starting from index x up to but not including the character at index y. If you want only to cut the string to length in python use only string[: length].


1 Answers

This is super simple with format:

>>> a = "John" >>> "{:<15}".format(a) 'John           ' 
like image 110
Games Brainiac Avatar answered Oct 07 '22 08:10

Games Brainiac