I am using Ubuntu 18.04 and Python 3.8
I need tuple_slice() to do 2 things:
- slice an input tuple between the given start and all BEFORE the end indexes
- Concatenate these values as a comma separated string
I've been able to do the second part
def tuple_slice(startIndex, endIndex, tup): tup = tup[startIndex:endIndex] print(tup) my_list = list(tup)#= [34, 13, 64] # I want to derive this using indexes print(my_list) my_string = ','.join(map(str, my_list)) print(my_string) return my_string
if __name__ == "__main__": print(tuple_slice(1, 4, (76, 34, 13, 64, 12)))Example, I want: 1st and 2nd parameters are the indexes, 3rd parameter is the tuple.
tuple_slice(1, 4, (76, 34, 13, 64, 12))to return:
34,13,64 1 2 Answers
This should solve your problem
def tuple_slice(startIndex, endIndex, tup): return ",".join (str(n) for n in tup[startIndex:endIndex])Using your example
[In]: print(tuple_slice(1, 4, (76, 34, 13, 64, 12)))
[Out]: 34,13,64 I think you are overcomplicating things a bit, you can do it in one step:
#!/usr/bin/env python3
def tuple_slice(start, end, tup): print(", ".join (str(n) for n in tup[start:end]))
tuple_slice(1, 4, (76, 34, 13, 64, 12))Shows:
34, 13, 64Or similar, if you need or want the string for further processing:
#!/usr/bin/env python3
def tuple_slice(start, end, tup): return ", ".join (str(n) for n in tup[start:end])
print(tuple_slice(1, 4, (76, 34, 13, 64, 12)))