Skip to content
Advertisement

Which way is better to concatenate strings in python? [closed]

def email_list(domains):
emails = []
for domain, users in domains.items():
  for user in users:
    emails.append(user + "@" + domain) # emails.append("{}@{}".format(user, domain))
return(emails)

Which way is better in this case and why?

  1. emails.append(user + “@” + domain)
  2. emails.append(“{}@{}”.format(user, domain))

Advertisement

Answer

In my honest opinion, f-strings are the best. They are flexible and readable. Unlike other concats, you don’t have to make sure you insert all strings. Infact, you can do something like that:

number = 9
text = "hello"
print(f"{text} {number}")

Also, it will automatically convert eventual quotes and special characters!

Globally, there isn’t a solution better than another. It’s all depending on the use case. But generally, fstrings are better.

Advertisement