Gita Gita - 1 year ago 80
Scala Question

How do I get a three digit range starting from 000 in scala? ex List.range(000, 200) output : List(000, 001, 002.... ,199)

I am writing a scala program to read 200 parquet files whose filenames have a pattern. I thought of using the range function but unfortunately in the range 000 is considered as 0.

val x = List.range(000, 200)

The print statement yeilds 0 as the output.
I want the list to have
(000, 001, 002, 003 ......., 198, 199)
. How can I achieve this?

Answer Source

There are many ways you could do this, but one of the simplest would be to use the f string interpolator:

val ids: IndexedSeq[String] = (0 until 200).map(i => f"$i%03d")

Which looks like this:

scala> ids.take(5).foreach(println)

The f part indicates that any variables in the following string literal should be interpolated with the provided format string. In this case our integer id is called i, and $i%03d says "interpolate the integral value i with width 3 and leading zeros if necessary".

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download