Extract run ids as strings, not ints

For every other entity, layout.get_* returns strings but for runs it returns integers. Is there a way to get strings instead?

The reason I need strings is that the specification allows run indices to have an arbitrary number of leading zeros. Therefore, I can’t reconstruct the path using integers.

Hi Evgenii,

I am not very familar with pybids, but in general you can convert an integer in strings just by doing something like:

>>> run = str(layout.get_run)
>>> run
2

if you want to add some zeros before the run (e.g., ‘004’), this is called zero padding and you can achieve it in several ways, one of them being:

>>> run = str(layout.get_run)
>>> print(run.zfill(2))  # add two zeros before the string
002

The above will works for strings. If you need to zero pad an int you can do like this instead:

>>> print(f'{run:02}')
02
>>> print(f'{run:04}')
0002

Yes, that is what I ended up doing. But that requires me to assume that there will be a certain number of leading zeros used in the dataset and I’d rather use the actual number.

If your desired output is [001, 002 … 011 … 999] you can use rjust:

>>> run = '3'
>>> print("The run value is: ", run)
The run value is:  3

>>> run_new = run.rjust(3, '0') 
>>> print ("The zero padded run value is: ", run_new)
The zero padded run value is:  003

note that run is a string, so in your code you can do everything in one line by doing

str(layout.get_run).rjust(3, '0')

where layout.get_run is an int, 3 is the desired output length and ‘0’ the character used for padding.

When creating a layout, bids uses a json config file to determine how entities are parsed. The default config file is pybids/bids/layout/config/bids.json in the pybids repository which is also found here on github. You can make a copy of this file and edit the run entity so that leading zeros are included. Here are the edits I made:

        {
            "name": "run",
            "pattern": "[_/\\\\]+run-(\\d+)"
        },

You then submit the edited json config file as an argument when creating a layout in python:

layout = BIDSLayout('/path/to/bids/folder', config='/path/to/edited_bids.json')

Thank you, @constantinoai, I want to avoid assuming the number of leading zeros, so converting back to string won’t work here.

Thank you, I will try that!