Ophethile
Ophethile

Reputation: 21

how to combine contents of one string to the contents of another string

this is my code:

 tasks_file = open("tasks.txt", "r+")
    for line in tasks_file:
        info = "Assigned to | Task | Task description | Date assigned | Due date | Task complete"
        string1 = info.split("|")
        for i in string1:
            print(i)
        string2 = line.split(",")
        for x in string2:
            print(x)
            
        output = i + ":" + x
        print(output) 

So basically what I'm trying to do is combine each separate item in string1 with each separate item in string2. But the code only combines the last separate items and not the whole thing. Please assist in any way that you can. Thanks

task file contents: admin, Register Users with taskManager.py, Use taskManager.py to add the usernames and passwords for all team members that will be using this program., 10 Oct 2019, 20 Oct 2019, No admin, Assign initial tasks, Use taskManager.py to assign each team member with appropriate tasks, 10 Oct 2019, 25 Oct 2019, No

desired output:(an example of how the output should be like)

Task:          Assign initial task
Assigned to:   Admin
Date assigned: 10 oct 2019
Due date:      25 oct 2019
Task complete: No

Upvotes: 1

Views: 125

Answers (1)

9769953
9769953

Reputation: 12261

outputs = []
for i, x in zip(string1, string2):
    outputs.append(i + ":" + x)
print(outputs)

outputs will be a list of the concatenated strings. You can combine the individual outputs together if you like with the str.join() method:

",".join(outputs)

will combine all the outputs together, with commas in between.


If you want to be fancy, you can do it all on nearly one line:

info = "Assigned to | Task | Task description | Date assigned | Due date | Task complete".split('|')
with open("tasks.txt") as fp:
    for line in fp:
        print(",".join(i + ":" + x for i, x in zip(info, line.split(','))))

But only if that doesn't confuse you or anyone else who reads your code.

Upvotes: 2

Related Questions