-2

def f(a, b,c,d):
    x = open('data.txt', 'r')
    for line in x:
        line = line[a:b] + ':' + line[c:d] + ':'
        x2 = open('data2.txt', 'a+')
        x2.writelines(line)
f(0,2,2,6)

I have raw data which is something like

1231231231231233453453223768729318974389124387\n
1234534534534543242145791208937867328918373892\n
8765432456765434568987692839471281027128012398\n
5787624567456787432343512487320190928390129383\n

I want to divide data based on their location for example: [0:2] could be column 1 and [2:6] is column 2 and so on. when I'm calling the function f(), Is there any way in python where we can overload or dynamically enter parameters like f(0,2,2,6,6,10,10,14.......)

output:

57:8762:4567:8743.....
  • 1
    Does this answer your question? [Can a variable number of arguments be passed to a function?](https://stackoverflow.com/questions/919680/can-a-variable-number-of-arguments-be-passed-to-a-function) – Edeki Okoh Jan 29 '20 at 17:07

1 Answers1

0

Yes. Python supports special input argument modifiers. The * says treat the argument as a list and assign any remaining input arguments to that list. (The ** says treat the arg as a dict and assign all keyword pairs to it.) So, you can have a func like:

def (a, b, *cd):
    "do something for 'a' and 'b'"
    for e in cd:
        "do something for each arg 'e' in 'cd'"

The arg 'cd' can be empty or it can be long, depending on what params you use to call the func. If you expect cd will always come in pairs, you can change the for loop to:

    for c, d in zip(cd[::2], cd[1::2]):
        "do something for 'c' and 'd'"

The zip function takes two lists and makes a list of tuples. So, the above for loop takes a single list and breaks it into pairs, an even and an odd. So, if 'cd' is (x0, y0, x1, y1), the zip call would yield ((x0, y0), (x1, y1)).

GaryMBloom
  • 5,350
  • 1
  • 24
  • 32