How to Left Align a Fixed Width String

How to left align a fixed width string?

You can prefix the size requirement with - to left-justify:

sys.stdout.write("%-6s %-50s %-25s\n" % (code, name, industry))

C printf: variable string column width, left align

To left-align the output in the width given, add a - sign to the format specifier

printf("%-*s %-*s %-*s %-*s %-*s %-*s %-*s %-*s %-*s\n", ... ); 

The arguments supplied for width can be a computed int value. You can hard-code the width like this

printf("%-10s\n", "string");

If you don't know how much space will be taken, you can use a temporary string

char tempstr[100];
int len = sprintf(tempstr, "%d", value);
printf("%s%-*s\n", tempstr, 30 - len, "string");

Printf left align and right align to obtain a fixed length string without truncation by varying space separators

You have all the strings with length. Take a piece of paper and draw it. For example:

[OK] |--------------------------------|  the whole space
|----| trailing part
|---------------------------| initial part = the whole space - trailing part

 width=40
printf "%s %-*s%s\n" "[OK]" "$((width - ${#3}))" "$2" "$3"

align right and left without knowing the string width

What you want are the adjustfield manipulators. This allows for both left and right justification.

There are three possible settings, internal, left and right.

For example:

std::cout.width( 10 ); std::cout << std::right << v << '\n';

How to print a string at a fixed width?

EDIT 2013-12-11 - This answer is very old. It is still valid and correct, but people looking at this should prefer the new format syntax.

You can use string formatting like this:

>>> print '%5s' % 'aa'
aa
>>> print '%5s' % 'aaa'
aaa
>>> print '%5s' % 'aaaa'
aaaa
>>> print '%5s' % 'aaaaa'
aaaaa

Basically:

  • the % character informs python it will have to substitute something to a token
  • the s character informs python the token will be a string
  • the 5 (or whatever number you wish) informs python to pad the string with spaces up to 5 characters.

In your specific case a possible implementation could look like:

>>> dict_ = {'a': 1, 'ab': 1, 'abc': 1}
>>> for item in dict_.items():
... print 'value %3s - num of occurances = %d' % item # %d is the token of integers
...
value a - num of occurances = 1
value ab - num of occurances = 1
value abc - num of occurances = 1

SIDE NOTE: Just wondered if you are aware of the existence of the itertools module. For example you could obtain a list of all your combinations in one line with:

>>> [''.join(perm) for i in range(1, len(s)) for perm in it.permutations(s, i)]
['a', 'b', 'c', 'd', 'ab', 'ac', 'ad', 'ba', 'bc', 'bd', 'ca', 'cb', 'cd', 'da', 'db', 'dc', 'abc', 'abd', 'acb', 'acd', 'adb', 'adc', 'bac', 'bad', 'bca', 'bcd', 'bda', 'bdc', 'cab', 'cad', 'cba', 'cbd', 'cda', 'cdb', 'dab', 'dac', 'dba', 'dbc', 'dca', 'dcb']

and you could get the number of occurrences by using combinations in conjunction with count().

best way to left-align strings after padding in python

words = ['var01', 'var02', 'var03']
label = 'Title: '
lines = ['{0}{1}'.format(label, words[0])] + ['{0}{1}'.format(' ' * len(label), w) for w in words[1:]]
print '\n'.join(lines)

How can I left-align strings using String.format()?

Same way as with printf -- use a - modifier in the format

expression for capturing aligned, fixed width fields of integers with failure on invalid succeeding characters

Here is a recipe you can use to force a regex expression to match a certain number of characters:

(?=.{LENGTH}(.*))EXPRESSION(?=\1$)

Example:

>>> # match 5 digits followed by "abc"
>>> pattern = re.compile(r'(?=.{5}(.*))\d+(?=\1$)abc')
>>> pattern.match('12345abc')
<_sre.SRE_Match object; span=(0, 8), match='12345abc'>
>>> pattern.match('123456abc')
>>>

If we combine this with a regex for non-zero integers padded with spaces on either side (\s*[+-]?0*[1-9]\d*\s*), it passes all the given test cases:

>>> pattern = re.compile(r'(?=.{5}(.*))\s*[+-]?0*[1-9]\d*\s*(?=\1$)')
>>> pattern.match('12345').group()
'12345'
>>> pattern.match('+2345678').group()
'+2345'
>>> pattern.match('-2345678').group()
'-2345'
>>> pattern.match(' +2345678').group()
' +234'
>>> pattern.match(' +2-345678')
>>> pattern.match(' 1')
>>>

What is this sorcery?

Let's take a closer look at this recipe:

(?=.{LENGTH}(.*))EXPRESSION(?=\1$)

First, the lookahead (?=.{LENGTH}(.*)) skips LENGTH characters with .{LENGTH}. Then (.*) captures all the remaining text in group 1. In other words, we've captured all the remaining text minus the first LENGTH characters.

Afterwards, EXPRESSION matches and (hopefully) consumes exactly LENGTH characters.

Finally, we use (?=\1$) to assert that capture group 1 matches. Since group 1 contains all remaining text minus LENGTH characters, this will only match if EXPRESSION has consumed exactly LENGTH characters. We have thus forced EXPRESSION to an exact length of LENGTH characters.



Related Topics



Leave a reply



Submit