TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: String Concatenation in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

String Concatenation in Python

Last updated: Feb 12, 2024 1:22 am
By Meenakshi Agarwal
Share
11 Min Read
7 ways of string concatenation in Python
SHARE

String concatenation in Python is the process of joining multiple strings together to create a single string. It’s like combining words to form sentences. In Python, we have various methods to achieve this.

Contents
Python + Operator to Concatenate StringsUse Python Join() to Concatenate StringsUsing F-StringsUsing % Sign for String Concatenation in PythonUsing String Format() FunctionUsing List Comprehension to Concatenate StringsUsing Str.Add() Method

We have listed down seven methods for string concatenation. They allow you to manipulate and format text data efficiently. Each section has the sample code so that you can easily absorb the logic. Here is the explanation of each method with code samples:

Python + Operator to Concatenate Strings

The plus (+) operator is the most common way to concatenate strings in Python. It is a binary operator, which means that it takes two operands. The operands in this case are the two strings that you want to concatenate.

The syntax for using the plus (+) operator to concatenate strings is as follows:

str1 + str2

where str1 and str2 are the two strings that you want to concatenate.

Here is an example of how to use the plus (+) operator for string concatenation in Python:

str1 = "Hello"
str2 = "World!"
result = str1 + " " + str2
print(result)

This code gives the following result:

Hello world!

Use Python Join() to Concatenate Strings

The Python join() method is a string method that takes a sequence of strings as its argument and joins them together with a specified separator. The separator defaults to an empty string. It means the join() method concatenates a sequence of strings without any separator.

The syntax for the join() method is as follows:

str.join(sequence)

where str is the separator string and sequence is the sequence of strings that we need to join.

Here is an example of how to use the join() method for string concatenation in Python:

str1 = "Hello "
str2 = "World!"

str3 = " ".join([str1, str2])

print(str3)

This code will print the same output as the previous code.

Using F-Strings

F-strings are a new feature in Python 3.6 that allows you to insert variables and expressions into strings using curly braces. They are a more concise and expressive way to format strings than the format() function.

The syntax for f-strings is as follows:

f"{expression}"

where expression is the expression that you want to insert into the string.

Here is an example of how to use f-strings for string concatenation in Python:

name = "World!"

str1 = f"Hello {name}!"

print(str1)

This code will also print the same output as the previous code. Also, you can see that f-strings are more compact and expressive to use.

Using % Sign for String Concatenation in Python

Combine strings with placeholders for variables, an older method.

This is an older way to format strings in Python, but Python 3 and above versions still support it.

To concatenate strings using the % operator, you can use the following syntax:

"%s %s" % (string1, string2)

where string1 and string2 are the strings that you want to concatenate.

Here is an example of how to use the % operator for string concatenation in Python.

str1 = "Hello"
str2 = "World!"

result = "%s %s" % (str1, str2)

print(result)

The above program gives the following output:

Hello World!

Using String Format() Function

The format() function is a versatile function that formats strings and fills in new text into them. It can also concatenate strings.

To concatenate strings using the format() function, you can use the following syntax:

f"{string1} {string2}"

where string1 and string2 are the strings that you want to concatenate.

Here is an example of how to use the format() function to concatenate strings:

str1 = "Hello"
str2 = "World!"

result = f"{str1} {str2}"

print(result)

This code will print the following output:

Hello world!

Using List Comprehension to Concatenate Strings

In general, the list comprehension in Python is a concise way to create a list. It can also be used to concatenate strings.

To concatenate strings using list comprehension, you can use the following syntax:

[str1 + str2 for str1, str2 in zip(strings1, strings2)]

The strings1 and strings2 arguments are the two lists of strings that you want to join. The zip() function takes the two lists and creates a new list of tuples, where each tuple contains one element from each list. The str1 + str2 expression concatenates the two strings in each tuple.

Here is an example of how to use list comprehension to concatenate strings:

strings1 = ["Hello ", "world!"]
strings2 = ["This is ", "a sentence."]

concatenated_strings = [str1 + str2 for str1, str2 in zip(strings1, strings2)]

print(concatenated_strings)

This code will print the following output:

['Hello This is ', 'world! a sentence.']

As you can see, list comprehension is a concise and easy way to concatenate strings. It can also concatenate strings from different lists.

Here are some other examples of how to use list comprehension to concatenate strings:

strings = ["This is a list of strings."]

concatenated_strings = [str + "." for str in strings]

print(concatenated_strings)

This code will print the following output:

['This is a list of strings..']

Let’s take another example where we are combining a list of strings and numbers.

numbers = [1, 2, 3]
strings = ["This is a list of numbers:", "1", "2", "3"]

# Use str() to convert integers to strings
concatenated_strings = [str1 + str(str2) for str1, str2 in zip(strings, numbers)]

print(concatenated_strings)

This code prints the following result:

['This is a list of numbers:1', '12', '23']

Using Str.Add() Method

The str.add() method is a special method in Python that is called when you use the plus (+) operator to concatenate two strings.

This method can be overridden in a Python class to provide custom string concatenation behavior.

The syntax for the string add() method is as follows:

def __add__(self, other):
  """Concatenates this string with another string.
  Args:
    other: The other string to concatenate with.
  Returns:
    A new string that is the concatenation of this string and the other string.
  """
  return <class name>(str(self) + other)

The ‘self’ argument is the current string object, and the other argument is the other string object to concatenate with. The return statement returns a new string that is the concatenation of the two strings.

Here is an example of how to override the string add() method:

class MyString(str):

  def __add__(self, other):
    """Concatenates this string with another string, reversing the order."""
    return MyString(str(self) + other)

This class defines a new MyString class that inherits from the str class. The add() method in this class reverses the order of the strings being concatenated.

class MyString(str):
    def __add__(self, other):
        """Concatenates this string with another string."""
        return MyString(str(self) + other)

str1 = MyString("Hello, ")
str2 = "world!"

str3 = str1 + str2  # This will use the custom __add__ method

print(str3)

This code will produce the following result:

Hello, world!

As you can see, the MyString class overrides the string add() method and concatenates the two strings.

Conclusion – String Concatenation in Python

Understanding these methods provides you with a versatile toolkit for handling strings in Python. Which of these you use to perform string concatenation will depend on your specific needs.

The plus (+) operator is the most common and straightforward method, but the join() method is more flexible and can be used to join a sequence of strings.

The format() function and f-strings are more powerful formatting tools that can be used to insert variables and expressions into strings.

The % operator is an older method that is still supported, but it is not as commonly used as the other methods.

Here are some additional things to keep in mind about string concatenation in Python:

  • Strings are immutable, so when you concatenate two strings, you are creating a new string that is the concatenation of the two original strings.
  • The order of the strings is important. The first string will be at the beginning of the new string, and the second string will be at the end.
  • You can concatenate strings with other types of data, such as numbers and lists. However, the results of this concatenation may not be what you expect. For example, if you concatenate a string with a number, the number will be converted to a string before the concatenation is performed.

I hope this helps! Let us know for any queries or feedback. Use the comment box or our contact page to reach out.

Happy coding!

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

Selenium Python Extent Report Guide

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article Random email generator for random email addresses Python Code to Generate Random Email
Next Article Python Print() Explained with Examples Python Print() with Examples

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x