Format a number as a string - python

How do you format a number as a string so that it takes a number of spaces in front of it? I want the shorter number 5 to have enough spaces in front of it so that the spaces plus the 5 have the same length as 52500. The procedure below works, but is there a built in way to do this?
a = str(52500)
b = str(5)
lengthDiff = len(a) - len(b)
formatted = '%s/%s' % (' '*lengthDiff + b, a)
# formatted looks like:' 5/52500'

Format operator:
>>> "%10d" % 5
' 5'
>>>
Using * spec, the field length can be an argument:
>>> "%*d" % (10,5)
' 5'
>>>

'%*s/%s' % (len(str(a)), b, a)

You can just use the %*d formatter to give a width. int(math.ceil(math.log(x, 10))) will give you the number of digits. The * modifier consumes a number, that number is an integer that means how many spaces to space by. So by doing '%*d' % (width, num)` you can specify the width AND render the number without any further python string manipulation.
Here is a solution using math.log to ascertain the length of the 'outof' number.
import math
num = 5
outof = 52500
formatted = '%*d/%d' % (int(math.ceil(math.log(outof, 10))), num, outof)
Another solution involves casting the outof number as a string and using len(), you can do that if you prefer:
num = 5
outof = 52500
formatted = '%*d/%d' % (len(str(outof)), num, outof)

See String Formatting Operations:
s = '%5i' % (5,)
You still have to dynamically build your formatting string by including the maximum length:
fmt = '%%%ii' % (len('52500'),)
s = fmt % (5,)

Not sure exactly what you're after, but this looks close:
>>> n = 50
>>> print "%5d" % n
50
If you want to be more dynamic, use something like rjust:
>>> big_number = 52500
>>> n = 50
>>> print ("%d" % n).rjust(len(str(52500)))
50
Or even:
>>> n = 50
>>> width = str(len(str(52500)))
>>> ('%' + width + 'd') % n
' 50'

Related

need help in understanding a code

Can anyone explain this code a little. I can't understand what n does here? We already have taken N = int(input()) as input then why n=len(bin(N))-2? I couldn't figure it out.
N = int(input())
n = len(bin(N))-2
for i in range(1,N+1):
print(str(i).rjust(n) + " " + format(i,'o').rjust(n) + " " + format(i,'X').rjust(n) + " " + format(i,'b').rjust(n))
n counts the number of bits in the number N. bin() produces the binary representation (zeros and ones), as as string with the 0b prefix:
>>> bin(42)
'0b101010'
so len(bin(n)) takes the length of that output string, minus 2 to account for the prefix.
See the bin() documentation:
Convert an integer number to a binary string prefixed with “0b”.
The length is used to set the width of the columns (via str.rjust(), which adds spaces to the front of a string to create an output n characters wide). Knowing how many characters the widest binary representation needs is helpful here.
However, the same information can be gotten directly from the number, with the int.bitlength() method:
>>> N = 42
>>> N.bit_length()
6
>>> len(bin(N)) - 2
6
The other columns are also oversized for the numbers. You could instead calculate max widths for each column, and use str.format() or an f-string to do the formatting:
from math import log10
N = int(input())
decwidth = int(log10(N) + 1)
binwidth = N.bit_length()
hexwidth = (binwidth - 1) // 4 + 1
octwidth = (binwidth - 1) // 3 + 1
for i in range(1, N + 1):
print(f'{i:>{decwidth}d} {i:>{octwidth}o} {i:>{hexwidth}X} {i:>{binwidth}b}')

How to place a number into a string?

I want to create the following function
Left_padded(n, width)
That returns, for example:
Left_padded(6, 4):
' 6' #number 6 into a 4 digits space
Left_padded(54, 5)
' 54' #number 54 into a 5 digits space
You can use rjust:
>>> def Left_padded(n, width):
... return str(n).rjust(width)
>>> Left_padded(54, 5)
' 54'
Assuming you want to put the number next to another string, you can also use % formatting to achieve the same result:
>>> w1 = "your number is:"
>>> num = 20
>>> line = '%s%10s' % (w1, num)
>>> print(line)
'your number is: 20'

Python: replace every letter except the nth letters in a string with a period(or another character)

So I have looked at the replace every nth letter and could not figure out the reverse. I started with this and quickly realized it would not work:
s = input("Enter a word or phrase: ")
l = len(s)
n = int(input("choose a number between 1 and %d: " %l))
print (s[0] + "." * (n-1)+ s[n]+ "." * (n-1) + s[n*2])
any help would be appreciated.
Let s be the original string and n the position not to be replaced.
''.join (c if i == n else '.' for i, c in enumerate (s) )
If the user enters 3, I'm assuming you want to replace the third, sixth, ninth...letter, right? Remember that indices are counted from 0:
>>> s = "abcdefghijklmnopqrstuvwxyz"
>>> remove = 3
>>> "".join(c if (i+1)%remove else "." for i,c in enumerate(s))
'ab.de.gh.jk.mn.pq.st.vw.yz'
Or, if you meant the opposite:
>>> "".join("." if (i+1)%remove else c for i,c in enumerate(s))
'..c..f..i..l..o..r..u..x..'
You can use reduce following way:
>>> s = "abcdefghijklmnopqrstuvwxyz"
>>> n=3
>>> print reduce(lambda i,x: i+x[1] if (x[0]+1)%n else i+".", enumerate(s), "")
ab.de.gh.jk.mn.pq.st.vw.yz
>>> print reduce(lambda i,x: i+"." if (x[0]+1)%n else i+x[1], enumerate(s), "")
..c..f..i..l..o..r..u..x..
Build from what you already know. You know how to find every nth character, and your result string will have all of those in it and no other character from the original string, so we can use that. We want to insert things between those, which is exactly what the str.join method does. You've already worked out that what to insert is '.' * n-1. So, you can do this:
>>> s = "abcdefghi"
>>> n = 3
>>> ('.' * (n-1)).join(s[::n])
'a..d..g'
The only trick is that you need to account for any characters after the last one that you want to leave in place. The number of those is the remainder when the highest valid index of s is divided by n - or, (len(s) - 1) % n. Which gives this slightly ugly result:
>>> ('.' * (n-1)).join(s[::n]) + '.' * ((len(s) - 1) % n)
'a..d..g..'
You probably want to use variables for the two sets of dots to help readability:
>>> dots = '.' * (n - 1)
>>> end_dots = '.' * ((len(s) - 1) % n)
>>> dots.join(s[::n]) + end_dots
'a..d..g..'
My tricky solution (I'll let you add comments):
s = 'abcdefghijklmnopqrstuvwxyz'
n = 3
single_keep_pattern = [False] * (n - 1) + [True]
keep_pattern = single_keep_pattern * ( len(s) / n + 1)
result_list = [(letter if keep else '.') for letter, keep in zip(s, keep_pattern)]
result = ''.join(result_list)
print result
gives:
..c..f..i..l..o..r..u..x..

How do I add character padding to a string?

Okay this is very hard to explain, but i want to add padding to a sentence so that the characters in that sentence are a multiple of n.
however this number '4' has to change to 3 and 5 so it has to work then as well..
anyone know what im talking about?? and how to do it?
I hope the self commented code below would help you grasp the concept. You just have to do some maths to get the pad characters at either end
Some concept
Extra Characters required Padding = len(string) % block_length
Total_Pad_Characters = block_length - len(string) % block_length
Pad Character's at front = Total_Pad_Characters/2
Pad Character's at end = Total_Pad_Characters - Total_Pad_Characters/2
So here is the code
>>> def encrypt(st,length):
#Reversed the String and replace all Spaces with 'X'
st = st[::-1].replace(' ','X')
#Find no of characters to be padded.
padlength = (length - len(st)%length) % length
#Pad the Characters at either end
st = 'X'*(padlength/2)+st+'X'*(padlength-padlength/2)
#Split it with size length and then join with a single space
return ' '.join(st[i:i+length] for i in xrange(0,len(st),length))
>>> encrypt('THE PRICE OF FREEDOM IS ETERNAL VIGILENCE', 4) #Your Example
'XECN ELIG IVXL ANRE TEXS IXMO DEER FXFO XECI RPXE HTXX'
>>> encrypt('THE PRICE', 5) # One Extra Character at end for Odd Numbers
'ECIRP XEHTX'
>>> encrypt('THE PRIC', 5) # 1 Pad Characters at either end
'XCIRP XEHTX'
>>> encrypt('THE PRI', 5) # 1 Pad Characters at either end and one Extra for being Odd
'XIRPX EHTXX'
>>> encrypt('THE PR', 5) # 2 Pad Characters at either end
'XXRPX EHTXX'
>>> encrypt('THE P', 5) # No Pad characters required
'PXEHT'
>>> encrypt('THE PRICE OF FREEDOM IS ETERNAL VIGILENCE', 5) #Ashwini's Example
'XXECN ELIGI VXLAN RETEX SIXMO DEERF XFOXE CIRPX EHTXX'
>>>
>>> import math
>>> def encrypt(string, length):
inverse_string = string.replace(' ','X')[::-1]
center_width = int(math.ceil(len(inverse_string)/float(length)) * length) # Calculate nearest multiple of length rounded up
inverse_string = inverse_string.center(center_width,'X')
create_blocks = ' '.join(inverse_string[i:i+length] for i in xrange(0,len(inverse_string),length))
return create_blocks
>>> encrypt('THE PRICE OF FREEDOM IS ETERNAL VIGILENCE', 4)
'XECN ELIG IVXL ANRE TEXS IXMO DEER FXFO XECI RPXE HTXX'
def pad(yourString,blockLength):
return yourString + ("X" * (blockLength - (len(yourString) % blockLength)))
Is your padding function. for end padding.
If you need center padding use:
def centerPad(yourString,blockLength):
return ("X" * ((blockLength - (len(yourString) % blockLength))/2)) + yourString + ("X" * ((blockLength - (len(yourString) % blockLength))/2))
you need to take a harder look at the rest of your code if you want to implement a block cypher.

Formatting in Python 2.7

I have a column formatting issue:
from math import sqrt
n = raw_input("Example Number? ")
n = float(n)
sqaureRootOfN = sqrt(n)
print '-'*50
print ' # of Decimals', '\t', 'New Root', '\t', 'Percent error'
print '-'*50
for a in range(0,10):
preRoot = float(int(sqaureRootOfN * 10**a))
newRoot = preRoot/10**a
percentError = (n - newRoot**2)/n*100
print ' ', a, '\t\t', newRoot, '\t\t', percentError, '%'
It comes out like:
Not in the same column!?!
#Bjorn has the right answer here, using the String.format specification. Python's string formatter has really powerful methods for aligning things properly. Here's an example:
from math import sqrt
n = raw_input("Example Number? ")
n = float(n)
sqaureRootOfN = sqrt(n)
print '-'*75
print ' # of Decimals', ' ' * 8, 'New Root', ' ' * 10, 'Percent error'
print '-'*75
for a in range(0,10):
preRoot = float(int(sqaureRootOfN * 10**a))
newRoot = preRoot/10**a
percentError = (n - newRoot**2)/n*100
print " {: <20}{: <25}{: <18}".format(a, newRoot, str(percentError) + ' %')
Note that instead of tabs I'm using spaces to space things out. This is because tabs are really not what you want to use here, because the rules for how tabs space things are inconsistent (and depend on what your terminal/viewer settings are).
This is what the answer looks like:
---------------------------------------------------------------------------
# of Decimals New Root Percent error
---------------------------------------------------------------------------
0 9.0 18.1818181818 %
1 9.9 1.0 %
2 9.94 0.198383838384 %
3 9.949 0.0175747474747 %
4 9.9498 0.00149490909092 %
5 9.94987 8.7861717162e-05 %
6 9.949874 7.45871112931e-06 %
7 9.9498743 1.4284843602e-06 %
8 9.94987437 2.14314187048e-08 %
9 9.949874371 1.33066711409e-09 %
Using str.format,
import math
n = float(raw_input("Example Number? "))
squareRootOfN = math.sqrt(n)
print('''\
{dashes}
{d:<16}{r:<15}{p:<}
{dashes}'''.format(dashes = '-'*50, d = ' # of Decimals', r = 'New Root', p = 'Percent error'))
for a in range(0,10):
preRoot = float(int(squareRootOfN * 10**a))
newRoot = preRoot/10**a
percentError = (n - newRoot**2)/n
print(' {d:<14}{r:<15}{p:13.9%}'.format(d = a, r = newRoot, p = percentError))
yields
--------------------------------------------------
# of Decimals New Root Percent error
--------------------------------------------------
0 9.0 18.181818182%
1 9.9 1.000000000%
2 9.94 0.198383838%
3 9.949 0.017574747%
4 9.9498 0.001494909%
5 9.94987 0.000087862%
6 9.949874 0.000007459%
7 9.9498743 0.000001428%
8 9.94987437 0.000000021%
9 9.949874371 0.000000001%
A few tricks/niceties:
Instead of three print statements, you can use one print statement on
a multiline string.
The percent symbol in the format {p:13.9%} lets you leave
percentError as a decimal (without multiplication by 100) and it
places the % at the end for you.
This is how tabs work. To get a correct formatting, you should use string.format. For your example, it could look like this:
print "{0:2d} {1:9.8f} {2:f} %".format(a, newRoot, percentError)

Categories

Resources