Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is there a quick python way to get a range response, if i type 1 it gives "1-10" and so on

I am getting into a problem statement for a script where i need to change int to a string with a range like 1-10 , 11-20 and so on. Using simple if else in python is not a good option for bugger numbers. Does someone know of any function to help out with this in python?

for example:

i am reading the numbers from a pandas dataframe each cell has different numbers:
so if i put the number in like the function-

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

convertnumtorange(1) it should give "1-10"
convertnumtorange(27) it should give "21-30"

>Solution :

Try this:

def convertnumtorange(n):
    b = (n - 1) // 10 * 10 + 10
    a = b - 9
    return f'{a}-{b}'

Examples:

>>> convertnumtorange(1)
'1-10'
>>> convertnumtorange(27)
'21-30'

Let’s say you have a data frame with numbers:

>>> import pandas as pd
>>> df = pd.DataFrame({'n': [1, 27]})
>>> df
    n
0   1
1  27
>>> df['range'] = df['n'].apply(convertnumtorange)
>>> df
    n  range
0   1   1-10
1  27  21-30
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading