Concatenate two strings python

Python String Concatenation [8 Methods]

In this Python tutorial, we will discuss how to concatenate strings in Python.

In Python, we can concatenate strings using 8 different methods. Now, all these methods are listed below.

  1. Using comma (,)
  2. Using the + operator
  3. Using concatenating literal strings
  4. Using the join() method
  5. Using the += operator
  6. Using the format() function
  7. Using f-string
  8. Using %-formatting

How to concatenate strings in python

Now, let us see how to concatenate strings in python, how to concatenate two strings in python. Also, can we add two strings in python?

Yes, we can add or concatenate strings. There are multiple ways to concatenate strings. See below for all the approaches

Method 1: How to concatenate strings in python using comma (,)

One of the basic ways to concatenate the strings in Python is by using the comma (,).

Here is an example of using comma (,) to concatenate strings in Python.

# Declaring string type variables myvar1 = "United" myvar2 = "States" # Using comma (,) to concatenate both strings print(myvar1, myvar2)

In the example, we used two string-type variables myvar1 and myvar2. And to concatenate them, we specified both the variable in the print() function separated by a comma (,).

Here is the result of the above Python program.

Method 2: How to concatenate strings in python using the + operator

Another common way to concatenate strings in Python is by using the + operator.

An example of using the + operator to concatenate strings is given below.

# Declaring string type variables myvar1 = "United" myvar2 = "States" # Using + operator to concatenate both strings concatenated_string = myvar1 + ' ' + myvar2 # Printing result print(concatenated_string)

Here we defined 2 string-type variables and then we used the plus (+) operator to concatenate the strings. However, we also added an empty string value between both the variables using plus (+) operator.

Читайте также:  Примеры математических программ на python

Once we execute the Python program, we will get the following result.

Method 3: How to concatenate strings in python using concatenating literal strings

In Python, we can concatenate literal strings by simply placing them next to each other, without any operator or function.

Let us look at an example of this in Python.

# Concatenating literal strings myvar = "New" " " "Zealand" # Printing result print(myvar)

In the above example, we used the concept of concatenating literal strings on “New” and “Zealand” strings together.

The result of the above Python program is given below.

Method 4: How to concatenate strings in python using the join() method

The join() is a method in Python that allows concatenating a sequence of strings into a single string using a specified separator.

Here is an example of using the join() method to concatenate Python Strings.

# Declaring string type variables myvar1 = "United" myvar2 = "States" # Using join() to concatenate both strings concatenated_string = " ".join([myvar1, myvar2]) # Printing result print(concatenated_string)

In the example, we are concatenating the myvar1 string with myvar2 using the join() method. However, we also specified

Method 5: How to concatenate strings in python using the += operator

The += is generally used to add values and calculate the sum. However, we can use the + operator on both strings and integers, we can use the += operator on strings to concatenate them.

An example of using the += operator on strings is given below.

# Declaring string type variables myvar1 = "United" myvar2 = "Kingdom" # Using += operator to concatenate both strings myvar1 += ' ' + myvar2 # Printing result print(myvar1)

In this example, we are concatenating the United and Kingdom strings using the += operator. The output of the above Python program is also shown below.

Method 6: How to concatenate strings in python using the format() function

The format() is a built-in function in Python utilized to format strings. With this function, we used the placeholders as curly brackets, and the format() function replaces the given string with the placeholders.

# Declaring string type variables myvar1 = "United" myvar2 = "States" # Using format() to concatenate both strings concatenated_string = "<> <>".format(myvar1, myvar2) # Printing result print(concatenated_string)

In the example, we concatenated the United string with States using the format() function.

Method 7: How to concatenate strings in python using f-string

In Python, f-string is short for formatted string literal and it is another way to format strings. This method includes expressions inside curly braces <> that are evaluated and replaced with their values at runtime.

Here is an example of using the f-string to concatenate 2 strings.

# Declaring string type variables myvar1 = "United" myvar2 = "Kingdom" # Using f-string to concatenate both strings concatenated_string = f" " # Printing result print(concatenated_string)

Once we execute the above Python program, we will get the following result.

Читайте также:  Java and ldap example

Method 8: How to concatenate strings in python using %-formatting

Just like format() function % formatting is another way to format string in Python. In this method, we use %s as the placeholder and it will replace the given string with the placeholder.

Here is an example of this approach in Python.

# Declaring string type variables myvar1 = "United" myvar2 = "Kingdom" # Using %-formatting to concatenate both strings concatenated_string = "%s %s" % (myvar1, myvar2) # Printing result print(concatenated_string)

Here is an example where we are concatenating 2 string values together to form the United Kingdom as the result.

concatenate strings in python

You may also like to read the following Python tutorials.

Conclusion

So, in this Python tutorial, we understood how to concatenate strings in Python. Moreover, we have covered 8 different methods to concatenate Python Strings.

Here is the list of 8 methods that we have covered in this tutorial.

  1. Using comma (,)
  2. Using the + operator
  3. Using concatenating literal strings
  4. Using the join() method
  5. Using the += operator
  6. Using the format() function
  7. Using f-string
  8. Using %-formatting

I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.

Источник

Как работает конкатенация строк в Python 3? Примеры.

Конкатенация строк — самая распространенная операция в программировании на Python. Есть несколько варинатов как сложить две строки.

Конкатенация строк в Python

Варианты обьединения строк:

  • + operator
  • метод join()
  • % оператор
  • функция format()
  • f-string (форматированные строковые литералы)

Конкатенация строк с помощью оператора ‘+’

Это самый простой способ. Давайте рассмотрим на примере:

s1 = 'Apple' s2 = 'Pie' s3 = 'Sauce' s4 = s1 + s2 + s3 print(s4)

Результат: «Pythonist.ru нужен Питонисту»

Давайте рассмотрим другой пример, где мы получаем 2 строки от пользователя и потом конкатенируем их.

s1 = input('Введите первую строку :\n') Введите первую строку : pythonist.ru s2 = input('Введите вторую строку:\n') Введите вторую строку: сайт для программистов print('Конкатенированная строка =', s1 + s2)
>>> s1 = input('Введите первую строку :\n') Введите первую строку : pythonist.ru >>> s2 = input('Введите вторую строку:\n') Введите вторую строку: сайт для программистов >>> print('Конкатенированная строка =', s1 + s2)

Результат: Конкатенированная строка = pythonist.ru сайт для программистов

Очень удобный способ использование оператора «+». Единственный момент, который надо учитывать это то, что обе вводные должны быть строками.

>>>'Hello' + 4 Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate str (not "int") to str

Мы можем использовать str() function для представленя объекта в виде строки.

Читайте также:  Питон удалить элемент словаря

Давайте посмотрим как конкатенировать строку и число или другой объект.

print('Питонист' + str(4)) class Data: def __init__(self, i): self.id = i def __str__(self): return 'Номер[' + str(self.id) + ']' print('Питонист ' + str(Data(10)))

Основная проблема оператора «+» в том, что используя его мы не можем добавить разделитель между строками. Например если мы хотим сконкатенировать строки “Hello” и “World” и поставить между ними пробел, то нам надо писать так «Hello» + » » + «World»

Конкатенация строк используя функцию join().

Мы можем использовать функцию join() для конкатенации строк и одновременного добавления разделителя между ними. Это полезная функция, когда мы имеем последовательность строк, например List или tuple строк.

Если вам не нужен разделитель, то можно использовать join() с пустой строкой.

s1 = 'Hello' s2 = 'World' print('Concatenated String using join() =', "".join([s1, s2])) print('Concatenated String using join() and whitespaces =', " ".join([s1, s2]))

Concatenated String using join() = HelloWorld

Concatenated String using join() and spaces = Hello World

Конкатенация строк используя оператор %

Мы можем использовать оператор % как для форматирования строк, так и для конкатенации. Он полезен когда нам нужно сложить две строки и вдобавок отфарматировать.

s1 = 'Hello' s2 = 'World' s3 = "%s %s" % (s1, s2) print('String Concatenation using % Operator =', s3) s3 = "%s %s from JournalDev - %d" % (s1, s2, 2018) print('String Concatenation using % Operator with Formatting =', s3)

String Concatenation using % Operator = Hello World

String Concatenation using % Operator with Formatting = Hello World from JournalDev — 2018

Конкатенация строк с помощью функции format()

Можно использовать функцию строк format() для конкатенации и форматирования.

s1 = 'Hello' s2 = 'World' s3 = "<>-<>".format(s1, s2) print('String Concatenation using format() =', s3) s3 = " ".format(in1=s1, in2=s2) print('String Concatenation using format() =', s3)

String Concatenation using format() = Hello-World
String Concatenation using format() = Hello World

Функция format() очень мощная и использовать ее только для сложения строк не самый лучший и быстрый вариант.

Конкатенация с использованием f-строк

Если вы используете Python3.6+ то вы можете использовать f-строки для конкатенации. Это новый способ форматирования строк. Он был представлен в PEP 498 – Literal String Interpolation.

s1 = 'Hello' s2 = 'World' s3 = f' ' print('String Concatenation using f-string =', s3) name = 'Pankaj' age = 34 d = Data(10) print(f' age is and d=')

String Concatenation using f-string = Hello World
Pankaj age is 34 and d=Data[10]

Python f-строки более чистый и легкий способ по сравнению с format()

Заключение

Форматирование строк в Python может быть сделано разными способами. Используйте один из них, в зависимости, что вам нужно сделать со строками. Если надо сконкатенировать и добавить разделитель, тогда используйте Join(). Если надо еще и отформатировать, тогда format() или f-строки. Учитывайте что f-строки можно использовать с версии Python3.6 или выше.

Источник

Оцените статью