Page 1 of 1

Using ljust to pad out strings

Posted: Sun Apr 23, 2017 6:05 pm
by RDS
I have been using the ljust command to pad out a string but I actually need to pad the string out with commas (,).
So far I have only been able to do it by assigning the comma to another string and then using that other string in the ljust command like this:

Code: Select all

d =','
ljust( myvariable, d)
This is because the format of the ljust command needs a comma to separate the 2 essential variables

Could someone please advise me if there is a better way.

Re: Using ljust to pad out strings

Posted: Sun Apr 23, 2017 6:51 pm
by ghp
Hello, some options I use are

Code: Select all

# right adjust
s = "{data:,>10s}".format(data="abc")
print("<" + s + ">")
# left adjust
s = "{data:,<10s}".format(data="abc")
print("<" + s + ">")
# join
s = "{data_0:s},{data_1:s}".format(data_0="abc", data_1="xyz")
print("<" + s + ">")
# ljust, rjust
print ( "<" + "abc".ljust(10, ",") + ">")
print ( "<" + "abc".rjust(10, ",") + ">")
Hope this helps, Gerhard

Re: Using ljust to pad out strings

Posted: Sun Apr 23, 2017 10:15 pm
by RDS
@Gerhard
I had tried a single inverted comma (') but not the double one.
That is just what I needed. Thank you very much.

Re: Using ljust to pad out strings

Posted: Sun Apr 23, 2017 10:40 pm
by paddyg

Code: Select all

'abc'.ljust(10, ',') #should work just as well (as " version), but I like format()