In Python, there are several ways to concatenate strings besides using the + operator. Here are some common methods:
-
Using
join()Method:first_name = "John" last_name = "Doe" full_name = " ".join([first_name, last_name]) -
Using f-strings (formatted string literals):
first_name = "John" last_name = "Doe" full_name = f"{first_name} {last_name}" -
Using
format()Method:first_name = "John" last_name = "Doe" full_name = "{} {}".format(first_name, last_name) -
Using
%Formatting:first_name = "John" last_name = "Doe" full_name = "%s %s" % (first_name, last_name) -
Using
StringIO(for multiple concatenations):from io import StringIO output = StringIO() output.write(first_name) output.write(" ") output.write(last_name) full_name = output.getvalue()
Each method has its use cases, and you can choose one based on your needs. If you have further questions or need examples, feel free to ask!
