Home > Software design >  How to display a list of values according to the positions given?
How to display a list of values according to the positions given?

Time:04-25

Supposed I have a string of randomly generated values,

string = 'ZlgKgIvhPGClfDtmaXjtqQMohOiNZuGaKwSyKsHAcAmpfDXOTUZIfwOvmlotZrquFDFvIvOZ'

and some positions as a list of tuples,

pxn = [(2, 10), (13, 20)]

where the tuples represent the starting and ending positions of the string.

I have been trying to write a function that would return segments of the string according to the positions given, so it'd look something like that

segment = ['lgKgIvhPG','fDtmaXjt']

I have had an attempt at it by doing something like this,

def find_region(string):
    " function that returns the string in segments by starting and ending positions provided" 
    for code, start, end in list:
        if index.string == start:
            if index.string == end:
                return code

which obviously does not work, but I don't really know how to proceed further. Any help would be much appreciated. Thank you.

CodePudding user response:

YOu can use this.

string = 'ZlgKgIvhPGClfDtmaXjtqQMohOiNZuGaKwSyKsHAcAmpfDXOTUZIfwOvmlotZrquFDFvIvOZ'
pxn = [(2, 10), (13, 20)]

segments = [string[start:end] for start,end in pxn]
print(segments)

output

['gKgIvhPG', 'DtmaXjt']

As numbering in python starts from 0 that means 0 points to the first index of the list. But If you want that 1 point to the first index of the list, Then you can use this one.

string = 'ZlgKgIvhPGClfDtmaXjtqQMohOiNZuGaKwSyKsHAcAmpfDXOTUZIfwOvmlotZrquFDFvIvOZ'
pxn = [(2, 10), (13, 20)]

segments = [string[start-1:end] for start,end in pxn]
print(segments)
    

But there is some caution if the user gives some value that is less than zero(0) or greater than the length of the string. Then this code does not work perfectly then you need to use this one.

string = 'ZlgKgIvhPGClfDtmaXjtqQMohOiNZuGaKwSyKsHAcAmpfDXOTUZIfwOvmlotZrquFDFvIvOZ'
pxn = [(2, 10), (13, 20)]

segments = [string[start:end] for start,end in pxn if start>0 and end<len(string)]
print(segments)

CodePudding user response:

You can use string slicing with a list comprehension to generate the desired output:

[string[start - 1:end] for start, end in pxn]

This outputs:

['lgKgIvhPG', 'fDtmaXjt']
  • Related