Join two string in python

Python String join()

Summary: in this tutorial, you’ll learn how to use the Python String join() method to concatenate strings in an iterable into one string.

Introduction to the Python String join() method

The string join() method returns a string which is the concatenation of strings in an iterable such as a tuple, a list, a dictionary, and a set.

The following shows the syntax of the join() method:

str.join(iterable)Code language: CSS (css)

The str will be the separator between elements in the result string.

If the iterable contains any non-string value, the join() method will raise a TypeError . To fix it, you need to convert non-string values to strings before calling the join() method.

The join() method has many practical applications. For example, you can use the join() method to compose a row for a CSV file.

Python string join examples

Let’s take some examples of using the string join() method.

1) Using string join() method to concatenate multiple strings into a string

The following example uses the string join() method to concatenate a tuple of strings without a separator:

colors = ('red', 'green', 'blue') rgb = ''.join(colors) print(rgb)Code language: PHP (php)

The following example uses the string join() method with the comma separator ( , ):

colors = ('red', 'green', 'blue') rgb = ','.join(colors) print(rgb)Code language: PHP (php)

2) Using string join() method to concatenate non-string data into a string

The following example uses the join() method to concatenate strings and numbers in a tuple to a single string:

product = ('Laptop', 10, 699) result = ','.join(product) print(result)Code language: PHP (php)
TypeError: sequence item 1: expected str instance, int foundCode language: JavaScript (javascript)

It issued a TypeError because the tuple product has two integers.

To concatenate elements in the tuple, you’ll need to convert them into strings before concatenating. For example:

product = ('Laptop', 10, 699) result = ','.join(str(d) for d in product) print(result)Code language: PHP (php)
  • First, use a generator expression to convert each element of the product tuple to a string.
  • Second, use the join() method to concatenate the string elements

Summary

Источник

How to Join Strings in Python 3

Programmers are destined to work with plenty of string data. This is partially because computer languages are tied to human language, we use one to create the other, and vice versa.

For this reason, it’s a good idea to master the ins and outs of working with strings early on. In Python, this includes learning how to join strings.

Manipulating strings may seem daunting, but the Python language includes tools that make this complex task easier. Before diving into Python’s toolset, let’s take a moment to examine the properties of strings in Python.

Читайте также:  Тег SELECT

A Little String Theory

As you may recall, in Python, strings are an array of character data.

An important point about strings is that they are immutable in the Python language. This means that once a Python string is created, it cannot be changed. Changing the string would require creating an entirely new string, or overwriting the old one.

We can verify this feature of Python by creating a new string variable. If we try to change a character in the string, Python will give us a Traceback Error.

>>> my_string = "Python For Beginners" >>> my_string[0] 'P' >>> my_string[0] = 'p' Traceback (most recent call last): File "", line 1, in TypeError: 'str' object does not support item assignment 

Its a good idea to keep the immutable quality of strings in mind when writing Python code.

While you can’t change strings in Python, you can join them, or append them. Python comes with many tools to make working with strings easier.

In this lesson, we’ll cover various methods for joining strings, including string concatenation. When it comes to joining strings, we can make use of Python operators as well as built-in methods.

As students progress, they’re likely to make use of each of these techniques in one way or another. Each has their own purpose.

Joining Strings with the ‘+’ Operator

Concatenation is the act of joining two or more strings to create a single, new string.

In Python, strings can be concatenated using the ‘+’ operator. Similar to a math equation, this way of joining strings is straight-forword, allowing many strings to be “added” together.

Let’s take a look at some examples:

# joining strings with the '+' operator first_name = "Bilbo" last_name = "Baggins" # join the names, separated by a space full_name = first_name + " " + last_name print("Hello, " + full_name + ".")

In our first example, we created two strings, first_name and last_name, then joined them using the ‘+’ operator. For clarity, we added space between the names.

Running the file, we see the following text in the Command Prompt:

The print statement at the end of the example shows how joining strings can generate text that is more legible. By adding punctuation through the power of concatenation, we can create Python programs that are easier to understand, easier to update, and more likely to be used by others.

Let’s look at another example. This time we’ll make use of a for loop to join our string data.

# some characters from Lord of the Rings characters = ["Frodo", "Gandalf", "Sam", "Aragorn", "Eowyn"] storyline = "" # loop through each character and add them to the storyline for i in range(len(characters)): # include "and" before the last character in the list if i == len(characters)-1: storyline += "and " + characters[i] else: storyline += characters[i] + ", " storyline += " are on their way to Mordor to destroy the ring." print(storyline) 

This more advanced example shows how concatenation can be used to generate human readable text from a Python list. Using a for loop, the list of characters (taken from the Lord of the Rings novels) is, one-by-one, joined to the storyline string.

A conditional statement was included inside this loop to check whether or not we’ve reached the last object in the list of characters. If we have, an additional “and” is included so that the final text is more legible. We’re also sure to include our oxford commas for additional legibility.

Frodo, Gandalf, Sam, Aragorn, and Eowyn, are on their way to Mordor to destroy the ring.

This method will NOT work unless both objects are stings. For instance, trying to join a string with a number will produce an error.

>>> string = "one" + 2 Traceback (most recent call last): File "", line 1, in TypeError: can only concatenate str (not "int") to str 

As you can see, Python will only let us concatenate a string to another string. It’s our jobs as programmers to understand the limitations of the languages we’re working with. In Python, we’ll need to make sure we’re concatenating the correct types of objects if we wish to avoid any errors.

Читайте также:  Php существует ли путь

Joining Lists with the ‘+’ Operator

The ‘+’ operator can also be used to join one or more lists of string data. For instance, if we had three lists, each with their own unique string, we could use the ‘+’ operator to create a new list combining elements from all three.

hobbits = ["Frodo", "Sam"] elves = ["Legolas"] humans = ["Aragorn"] print(hobbits + elves + humans) 

As you can see, the ‘+’ operator has many uses. With it, Python programmers can easily combine string data, and lists of strings.

Joining Strings with the .join() Method

If you’re dealing with an iterable object in Python, chances are you’ll want to use the .join() method. An iterable object, such as a string or a list, can be easily concatenated using the .join() method.

Any Python iterable, or sequence, can be joined using the .join() method. This includes, lists and dictionaries.

The .join() method is a string instance method. The syntax is as follows:

Here’s an example of using the .join() method to concatenate a list of strings:

numbers = ["one", "two", "three", "four", "five"] print(','.join(numbers)) 

Running the program in the command prompt, we’ll see the following output:

The .join() method will return a new string that includes all the elements in the iterable, joined by a separator. In the previous example, the separator was a comma, but any string can be used to join the data.

numbers = ["one", "two", "three", "four", "five"] print(' and '.join(numbers))

We can also use this method to join a list of alphanumeric data, using an empty string as the separator.

title = ['L','o','r','d',' ','o','f',' ','t','h','e',' ','R','i','n','g','s'] print(“”.join(title)) 

The .join() method can also be used to get a string with the contents of a dictionary. When using .join() this way, the method will only return the keys in the dictionary, and not their values.

number_dictionary = print(', '.join(number_dictionary)) 

When joining sequences with the .join() method, the result will be a string with elements from both sequences.

Copying Strings with ‘*’ Operator

If you need to join two or more identical strings, it’s possible to use the ‘*’ operator.

With the ‘*’ operator, you can repeat a string any number of times.

fruit = “apple” print(fruit * 2)

The ‘*’ operator can be combined with the ‘+’ operator to concatenate strings. Combining these methods allows us to take advantage of Python’s many advanced features.

fruit1 = "apple" fruit2 = "orange" fruit1 += " " fruit2 += " " print(fruit1 * 2 + " " + fruit2 * 3) 

Splitting and Rejoining Strings

Because strings in Python are immutable, it’s quite common to split and rejoin them.

Читайте также:  Php curl disable gzip

The .split() method is another string instance method. That means we can call it off the end of any string object.

Like the .join() method, the .split() method uses a separator to parse the string data. By default, whitespace is used as the separator for this method.

Let’s take a look at the .split() method in action.

names = "Frodo Sam Gandalf Aragorn" print(names.split()) 

This code outputs a list of strings.

['Frodo', 'Sam', 'Gandalf', 'Aragorn']

Using another example, we’ll see how to split a sentence into its individual parts.

story = "Frodo took the ring of power to the mountain of doom." words = story.split() print(words) 

Using the .split() method returns a new iterable object. Because the object is iterable, we can use the .join() method we learned about earlier to “glue” the strings back together.

original = "Frodo took the ring of power to the mountain of doom." words = original.split() remake = ' '.join(words) print(remake) 

By using string methods in Python, we can easily split and join strings. These methods are crucial to working with strings and iterable objects.

Tying Up the Loose Ends

By now, you should have a deeper knowledge of strings and how to use them in Python 3. Working through the examples provided in this tutorial will be a great start on your journey to mastering Python.

No student, however, can succeed alone. That’s why we’ve compiled a list of additional resources provided by Python For Beginners to help you complete your training.

With help, and patience, anyone can learn the basics of Python. If working to join strings in Python seems daunting, take some time to practice the examples above. By familiarizing yourself with string variables, and working with methods, you’ll quickly tap into the unlimited potential of the Python programming language.

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Источник

Python String join() Method

Join all items in a tuple into a string, using a hash character as separator:

myTuple = («John», «Peter», «Vicky»)

Definition and Usage

The join() method takes all items in an iterable and joins them into one string.

A string must be specified as the separator.

Syntax

Parameter Values

Parameter Description
iterable Required. Any iterable object where all the returned values are strings

More Examples

Example

Join all items in a dictionary into a string, using the word «TEST» as separator:

Note: When using a dictionary as an iterable, the returned values are the keys, not the values.

Unlock Full Access 50% off

COLOR PICKER

colorpicker

Join our Bootcamp!

Report Error

If you want to report an error, or if you want to make a suggestion, do not hesitate to send us an e-mail:

Thank You For Helping Us!

Your message has been sent to W3Schools.

Top Tutorials
Top References
Top Examples
Get Certified

W3Schools is optimized for learning and training. Examples might be simplified to improve reading and learning. Tutorials, references, and examples are constantly reviewed to avoid errors, but we cannot warrant full correctness of all content. While using W3Schools, you agree to have read and accepted our terms of use, cookie and privacy policy.

Источник

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