RDS
Posts: 776
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Using ljust to pad out strings

Sun Apr 23, 2017 6:05 pm

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.

ghp
Posts: 1516
Joined: Wed Jun 12, 2013 12:41 pm
Location: Stuttgart Germany
Contact: Website

Re: Using ljust to pad out strings

Sun Apr 23, 2017 6:51 pm

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

RDS
Posts: 776
Joined: Tue Oct 06, 2015 8:17 am
Location: Lancashire, UK

Re: Using ljust to pad out strings

Sun Apr 23, 2017 10:15 pm

@Gerhard
I had tried a single inverted comma (') but not the double one.
That is just what I needed. Thank you very much.

User avatar
paddyg
Posts: 2554
Joined: Sat Jan 28, 2012 11:57 am
Location: UK

Re: Using ljust to pad out strings

Sun Apr 23, 2017 10:40 pm

Code: Select all

'abc'.ljust(10, ',') #should work just as well (as " version), but I like format()
also https://groups.google.com/forum/?hl=en-GB&fromgroups=#!forum/pi3d

Return to “Python”