python syntax for formatting integer - python

I am new in python. In the following line
'{0:6}{1:02d}'.format(date, hour)
I figured out that hour should be 0 filled to two digits. But I can't figure out what it is formatting date to be. afaik, both date and hour are int values here.

{0:6} is just going to take the 0th argument (date) and print it with a minimum of 6 characters. It can be an integer, a string, ... Nothing else special there. It is a guess at what format was intended for date (ie. May1st, 5/1, ...)
You are correct about the interpretation of the {1:02d} which is the hour field print in a minimum of 2 decimal digits with 0's to pad.

Try it and see:
a = 10
b = 6
print('{0:6}{1:02}'.format(a, b))
#output => ' 1006'
So like 02 adds "0"s to the variable until it is of 2 length. Just adding a number (6) will add spaces to the front until the variable length is 6.
Python's Common String Operator's Docs has more.

Related

Keep zero digit save while converting string to integer in python

I am converting a string into integer using int function and it is working fine but i want to keep save zero digit that are at the start of the string.
string_value = '0123'
print(int(string_value))
result is 123
How can i format output 0123 as in integer type value not in string.
You can't, but if you want to put 0's (zero padding) at the beginning of your number, this is the way to do it.
"{:04}".format(123)
# '0123'
"{:05}".format(123)
# '00123'
Like every one said you can try above answers or the following :
string_value = '0123'
int_no = int(string_value)
print("%04d" % int_no)
print(string_value.zfill(4))
Both will give same answer
Impossible, you cannot get an integer value of 0123.
You should change your mind, you do not actually need 0123 in integer, but you need to keep zero when displaying it. So the question should change to how to format output.

How to increment a numeric string in Python

I've spent the last two days trying to figure out how to increment a numeric string in Python. I am trying to increment a sequence number when a record is created. I spent all day yesterday trying to do this as an Integer, and it works fine, but I could never get database to store leading zeros. I did extensive research on this topic in StackOverflow, and while there are several examples of how to do this as an Integer and store leading zeros, none of the examples worked for me. Many of the examples were from 2014, so perhaps the methodology has changed. I then switched over to a String and changed my attribute to a CharField, and can get the function to work with leading zeros, but now I can't seem to get it to increment. Again, the examples that I found on SO were from 2014, so maybe things have changed a bit. Here is the function that works, but every time I call it, it doesn't increment. It just returns 00000001. I'm sure it's something simple I'm not doing, but I'm out of ideas. Thanks in advance for your help. Here is the function that works but doesn't increment.
def getNextSeqNo(self):
x = str(int(self.request_number) + 1)
self.request_number = str(x).zfill(8)
return self.request_number
Here is the field as it's defined:
request_number = models.CharField(editable=True,null=True,max_length=254,default="00000")
I added a default of "00000" as the system is giving me the following error if it is not present:
int() argument must be a string, a bytes-like object or a number, not 'NoneType'
I realize the code I have is basically incrementing my default by 1, which is why I'm always getting 00000001 as my sequence number. Can't seem to figure out how to get the current number and then increment by 1. Any help is appreciated.
A times ago I made something similar
You have to convert your string to int and then you must to get its length and then you have to calculate the number of zeros that you need
code = "00000"
code = str(int(code) + 1 )
code_length = len(code)
if code_length < 5: # number five is the max length of your code
code = "0" * (5 - code_length) + code
print(code)
Can this be done? Yes. But don't do it.
Make it an integer.
Incrementing is then trivial - automatic if you make this the primary key. For searching, you convert the string to an integer and search the integer - that way you don't have to worry how many leading zeros were actually included as they will all be ignored. Otherwise you will have a problem if you use 6 digits and the user can't remember and puts in 6 0's + the number and then doesn't get a match.
For those who want to just increase the last number in a string.
Import re
a1 = 'name 1'
num0_m = re.search(r'\d+', str(a1))
if num0_m:
rx = r'(?<!\d){}(?!\d)'.format(num0_m.group())
print(re.sub(rx, lambda x: str(int(x.group()) + 1), a1))
number = int('00000150')
('0'*7 + str(number+1))[-8:]
This takes any number, adds 1, concatenates/joins it to a string of several (at least 7 in your case) zeros, and then slices to return the last 8 characters.
IMHO simpler and more elegant than measuring length and working out how many zeros to add.

Add zeros as prefix to a calculated value based on the number of digits

I have written an expression which will ask for a user input. Based on the user input, it will calculate a value. If the calculated value is say 1, then I want the value to be converted to 0001. Same thing applies when the calculated value is 2 and 3 digits long.
If the calculated value is 4 or 5 digits long, then I don't want any modification on it. This value is used in the later part of the program which I have not mentioned here.
import numpy as np
FT_init = 3.1212
delt = 0.15
TS_init = 165
flowtime = input("Enter the flow time required: ")
timestep = (flowtime-FT_init)/delt
timestep = round(timestep + TS_init)
print timestep
I request your help on this.
You may use zfill() string method:
str(timestep).zfill(4)
This is more or less similar to the other answer.
i = 9
print("{:05d}".format(i))
just change the print to use a format string:
print '%04d' % int(timestep)
that will zero fill left, and allow it to show 5 digits without problem
however you cannot use that output in any kind of calculations since converting back to a number will strip the left zeros and possibly use it as an octal number - which will cause a conversion error if there are digits that would not be valid octal i.e. 0397
Use the string.format() method. The following format specification, '{:04}', says replace that with the argument n from format(n) and then format it, :, with leading zeros, 0, printing at least 4, 4, digits.
Example with numbers of different printed widths:
for n in [1, 12, 123, 1234, 12345, 123456]:
print('{:04}'.format(n))
Output:
0001
0012
0123
1234
12345
123456

Strings, ints and leading zeros

I need to record SerialNumber(s) on an object. We enter many objects. Most serial numbers are strings - the numbers aren't used numerically, just as unique identifiers - but they are often sequential. Further, leading zeros are important due to unique id status of serial number.
When doing data entry, it's nice to just enter the first "sequential" serial number (eg 000123) and then the number of items (eg 5) to get the desired output - that way we can enter data in bulk see below:
Obj1.serial = 000123
Obj2.serial = 000124
Obj3.serial = 000125
Obj4.serial = 000126
Obj5.serial = 000127
The problem is that when you take the first number-as-string, turn to integer and increment, you loose the leading zeros.
Not all serials are sequential - not all are even numbers (eg FDM-434\RRTASDVI908)
But those that are, I would like to automate entry.
In python, what is the most elegant way to check for leading zeros (*and, I guess, edge cases like 0009999) in a string before iterating, and then re-application of those zeros after increment?
I have a solution to this problem but it isn't elegant. In fact, it's the most boring and blunt alg possible.
Is there an elegant solution to this problem?
EDIT
To clarify the question, I want the serial to have the same number of digits after the increment.
So, in most cases, this will mean reapplying the same number of leading zeros. BUT in some edge cases the number of leading zeros will be decremented. eg: 009 -> 010; 0099 -> 0100
Try str.zfill():
>>> s = "000123"
>>> i = int(s)
>>> i
123
>>> n = 6
>>> str(i).zfill(n)
'000123'
I develop my comment here, Obj1.serial being a string:
Obj1.serial = "000123"
('%0'+str(len(Obj1.serial))+'d') % (1+int(Obj1.serial))
It's like #owen-s answer '%06d' % n: print the number and pad with leading 0.
Regarding '%d' % n, it's just one way of printing. From PEP3101:
In Python 3.0, the % operator is supplemented by a more powerful
string formatting method, format(). Support for the str.format()
method has been backported to Python 2.6.
So you may want to use format instead… Anyway, you have an integer at the right of the % sign, and it will replace the %d inside the left string.
'%06d' means print a minimum of 6 (6) digits (d) long, fill with 0 (0) if necessary.
As Obj1.serial is a string, you have to convert it to an integer before the increment: 1+int(Obj1.serial). And because the right side takes an integer, we can leave it like that.
Now, for the left part, as we can't hard code 6, we have to take the length of Obj1.serial. But this is an integer, so we have to convert it back to a string, and concatenate to the rest of the expression %0 6 d : '%0'+str(len(Obj1.serial))+'d'. Thus
('%0'+str(len(Obj1.serial))+'d') % (1+int(Obj1.serial))
Now, with format (format-specification):
'{0:06}'.format(n)
is replaced in the same way by
('{0:0'+str(len(Obj1.serial))+'}').format(1+int(Obj1.serial))
You could check the length of the string ahead of time, then use rjust to pad to the same length afterwards:
>>> s = "000123"
>>> len_s = len(s)
>>> i = int(s)
>>> i
123
>>> str(i).rjust(len_s, "0")
'000123'
You can check a serial number for all digits using:
if serial.isdigit():

Need Help on String Formatting

I've written this program in Python 3 that takes a CSV file that finds the min and max death rates for particular states.
I've basically finished the program and it outputs correctly in the shell, but I have a problem:
Different states have different lengths of characters in their names and the spacing does come out correctly, how do I use string formatting to make the strings space evenly regardless of the number of characters printed?
Here is what I have:
print ("\n", "Indicator |", "Min ",
" | Max ")
print ("-----------------------------------------------------------------------------------------------")
This is the output:
It works well for "Minnesota" but for "District of Columbia" it doesn't format evenly.
Any suggestions? Thanks.
Use string formatting as described here: http://docs.python.org/release/3.1.5/library/string.html
e.g.:
print('{:20} | {:20} {:5.2f} | {:20} {:5.2f}'.format(title, states[statemin], minimum, states[statemax], maximum))
Replace 20 with the longest string that will ever occur.
Note that I am assuming that minimum and maximum are floats, if they are strings, you cannot use '{:x.yf}' notation and you could just use {:6} or something like that instead.
{:20} means that 20 characters of space is used for the string, even if it is shorter (it does not truncate when longer). {:5.2f} means that 5 spaces are used for the float, of which 2 are after the decimal point.

Categories

Resources