-3

I'm writing a code to take a rain time-series and save hourly files for each day in order to feed a hydrological model, so, basically, I need to save each file with the hour of the day with tho digits, like this:

rain_20200101_0000.txt
rain_20200101_0100.txt
...
rain_20200101_0900.txt
rain_20200101_1000.txt
..
rain_20200101_2300.txt

But python doesn't put a zero before numbers between 0-9, so if I use a range(24) to do that it will save the first 10 hours like "rain_20200101_100.txt"

The solution I found was to put an if for x<10 and x>=10 inside the range(24) and insert a "0" before the hour for the first condition, but I think that is too rude and should be a more eficient way to do that. Could you help me with a simpler solution for this code?

namgold
  • 1,009
  • 1
  • 11
  • 32
dmildem
  • 25
  • 5

3 Answers3

0

Use string formatting to pad with zeros, e.g. "rain_%04d.txt" %(i).

gspr
  • 11,144
  • 3
  • 41
  • 74
0

Try this

"123".rjust(4, "0") # 0123

see this treasure on formatting

Ahmed I. Elsayed
  • 2,013
  • 2
  • 17
  • 30
0

Simple and sweet

>>> '{:04d}'.format(5)
'0005'
JenilDave
  • 606
  • 6
  • 14