Andile.M
Andile.M

Reputation: 9

TypeError: can only concatenate str (not "dict") to str

All my variables seem to be string data types however I keep getting the above error message

elif menu == 'a':
    pass
    user_1 = input("Please enter a user name: ")

    task_title = input("Please enter a title for the task to be done: ")
    task_desc = input("Please describe the task: ")
    task_due  = input("Please enter due date of the task: ")
    date_assign = str(date.today())
    with open("task.txt", "a") as fa:
        fa.write("\n" + {} + {} + {} + {} + {} + "No".format(task_title,task_desc,task_due,str(date_assign)))

Upvotes: 0

Views: 7135

Answers (3)

Richard
Richard

Reputation: 425

To add on to Nathan Robert's answer, consider using f-strings like so:

with open("task.txt", "a") as fa:
    fa.write(f"\n{task_title} {task_desc} {task_due} {date_assign} No")

I find them to be much cleaner then '+' string concatenation.

Upvotes: 2

Chris
Chris

Reputation: 36496

You cannot create a format string with:

"\n" + {} + {} + {} + {} + {} + "No"

You could:

"\n" + repr({}) + repr({}) + repr({}) + repr({}) + repr({}) + "No"

Which will yield:

"\n{}{}{}{}{}No"

But if you want:

"\n + {} + {} + {} + {} + {} + No"

Then you just need to eliminate two "s.

"\n + {} + {} + {} + {} + {} + No"

Also note that you've provided 5 sets of brackets, but only four arguments to format. This suggests a possible error on your part.

Upvotes: 0

Nathan Roberts
Nathan Roberts

Reputation: 838

Your brackets need to actually be within the string itself in order to use the str.format() function. So your code line:

fa.write("\n" + {} + {} + {} + {} + {} + "No".format(task_title,task_desc,task_due,str(date_assign)))

should look more like this:

fa.write("\n{} {} {} {} No".format(task_title,task_desc,task_due,str(date_assign)))

Upvotes: 2

Related Questions