Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to add X number of spaces to a string [duplicate]

Tags:

Probably an easy question that I couldn't quite find answer to before...

I'm formatting a table (in text) to look like this:

Timestamp: Word                        Number 

The number of characters between the : after timestamp and the beginning of Number is to be 20, including those in the Word (so it stays aligned). Using python I've done this:

    offset = 20 - len(word)      printer = timestamp + ' ' + word     for i in range(0, offset):         printer += ' '     printer += score 

Which works, but python throws an error at me that i is never used ('cause it's not). While it's not a huge deal, I'm just wondering if there's a better way to do so.

Edit:

Since I can't add an answer to this (as it's marked duplicate) the better way to replace this whole thing is

printer = timestamp + ' ' + word.ljust(20) + score 
like image 560
Mitch Avatar asked May 23 '14 18:05

Mitch


People also ask

How do I add extra space to a string?

To add a space between the characters of a string, call the split() method on the string to get an array of characters, and call the join() method on the array to join the substrings with a space separator, e.g. str. split(''). join(' ') .

How do you add multiple 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 add a specific number of spaces to a string in Java?

Use the padEnd() and padStart() methods to add spaces to the end or beginning of a string, e.g. str. padEnd(6, ' '); . The methods take the maximum length of the new string and the fill string and return the padded string.

How do you add multiple spaces in Javascript?

Use   It is the entity used to represent a non-breaking space. It is essentially a standard space, the primary difference being that a browser should not break (or wrap) a line of text at the point that this occupies.


1 Answers

You can multiply by strings by numbers to replicate them.

    printer += ' ' * offset 
like image 88
merlin2011 Avatar answered Oct 21 '22 01:10

merlin2011