What are other ways to concatenate strings?

0111

In Python, there are several ways to concatenate strings besides using the + operator. Here are some common methods:

  1. Using join() Method:

    first_name = "John"
    last_name = "Doe"
    full_name = " ".join([first_name, last_name])
  2. Using f-strings (formatted string literals):

    first_name = "John"
    last_name = "Doe"
    full_name = f"{first_name} {last_name}"
  3. Using format() Method:

    first_name = "John"
    last_name = "Doe"
    full_name = "{} {}".format(first_name, last_name)
  4. Using % Formatting:

    first_name = "John"
    last_name = "Doe"
    full_name = "%s %s" % (first_name, last_name)
  5. 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!

0 Comments

no data
Be the first to share your comment!