Wiki source for PythonStrings


Show raw source

=====Python Strings=====
return to DevPython

====Formatting====
In formatting patterns below, L is an int variable representing length
===Strings===
Right-Padded: %-Ls where L is length
%%
>>> '%-10s' % 'hello'
'hello '
%%
Left-Padded Truncated: %-Ls % string[:L]
%%
>>> '%-4s' % 'hello'
'hello'
>>> '%-4s' % 'hello'[:4]
'hell'
%%
Left-Padded: % Ls (note space)
%%
>>> '% 10s' % 'hello'
' hello'
%%
===Numbers===
Simple Integer: %d or %i
%%
>>> 'int: %d' % 200
'int: 200'
>>> 'int: %i' % 200
'int: 200'
%%
Zero-Padding Integer: %0Ld or %0Li
%%
>>> '%010d' % 200
'0000000200'
>>> '%010i' % 200
'0000000200'
%%
Simple Float: %.Df
%%
>>> 'float: %.2f' % 200.055
'float: 200.06'
%%
Float-Rounding: %L.Df (L is total string length, D decimal length)
%%
>>> '%10.2f' % 200
' 200.00'
>>> '%10.2f' % 200.055
' 200.06'
>>> '%10.2f' % 200.054
' 200.05'
%%
Zero-Padded Float-Rounding: %0L.Df
%%
>>> '%010.2f' % 200
'0000200.00'
%%
===Complex===
%%
>>> label = 'ABCDEFGHIJKLMNOPQR20'
>>> val1 = 123456789
>>> val2 = 123456789.12345
>>> '%-15s % 6d % 9.2f' % (label, val1, val2)
'ABCDEFGHIJKLMNOPQR20 123456789 123456789.12'
>>> '%-15s % 6d % 9.2f' % (label[:15], val1, val2)
'ABCDEFGHIJKLMNO 123456789 123456789.12'
%%
===Dictionary===
%%
>>> f = '%(label)s %(val1)6d %(val2)9.2f'
>>> label = 'ABCDEFGHIJKLMNOPQR20'
>>> val1 = 123456789
>>> val2 = 123456789.12345
>>> f % {'label':label[:15], 'val1':val1, 'val2':val2}
'ABCDEFGHIJKLMNO 123456789 123456789.12'
%%

====String Diffs====
%%(python)
from difflib import Differ
d = Differ()
print '\n'.join(list(d.compare(app_output, expect)))
%%

====References====
http://docs.python.org/library/stdtypes.html#string-formatting-operations
Valid XHTML 1.0 TransitionalValid CSSWikkaWiki