Split and join in python

Python program to split and join a string

Python program to Split a string based on a delimiter and join the string using another delimiter. Splitting a string can be quite useful sometimes, especially when you need only certain parts of strings. A simple yet effective example is splitting the First-name and Last-name of a person. Another application is CSV(Comma Separated Files). We use split to get data from CSV and join to write data to CSV. In Python, we can use the function split() to split a string and join() to join a string. For a detailed articles on split() and join() functions, refer these : split() in Python and join() in Python. Examples :

Split the string into list of strings Input : Geeks for Geeks Output : ['Geeks', 'for', 'Geeks'] Join the list of strings into a string based on delimiter ('-') Input : ['Geeks', 'for', 'Geeks'] Output : Geeks-for-Geeks

Below is Python code to Split and Join the string based on a delimiter :

Python3

['Geeks', 'for', 'Geeks'] Geeks-for-Geeks

Method: In Python, we can use the function split() to split a string and join() to join a string. the split() method in Python split a string into a list of strings after breaking the given string by the specified separator. Python String join() method is a string method and returns a string in which the elements of the sequence have been joined by the str separator.

Читайте также:  Restful api with python

Python3

['Geeks', 'for', 'Geeks'] Geeks-for-Geeks

Time complexity: O(n), where n is the length of given string
Auxiliary space: O(n)

Method: Here is an example of using the re module to split a string and a for loop to join the resulting list of strings:

Python3

# Split the string using a regular expression to match any sequence of non-alphabetic characters as the delimiter

['Geeks', 'for', 'Geeks'] Geeks-for-Geeks

In the above code, we first imported the re (regular expression) module in order to use the split() function from it. We then defined a string s which we want to split and join using different delimiters.

To split the string, we used the split() function from the re module and passed it the delimiter that we want to use to split the string. In this case, we used a space character as the delimiter. This function returns a list of substrings, where each substring is a part of the original string that was separated by the delimiter.

To join the list of substrings back into a single string, we used a for loop to iterate through the list. For each substring in the list, we concatenated it to a new string called new_string using the + operator. We also added a hyphen between each substring, to demonstrate how to use a different delimiter for the join operation.

Finally, we printed both the split and joined versions of the string to the console. The output shows that the string was successfully split and joined using the specified delimiters.

Method: Using regex.findall() method

Here we are finding all the words of the given string as a list (splitting the string based on spaces) using regex.findall() method and joining the result to get the result with hyphen

Источник

Python String split() and join() Methods – Explained with Examples

Bala Priya C

Bala Priya C

Python String split() and join() Methods – Explained with Examples

When working with strings in Python, you may have to split a string into substrings. Or you might need to join together smaller chunks to form a string. Python’s split() and join() string methods help you do these tasks easily.

In this tutorial, you’ll learn about the split() and join() string methods with plenty of example code.

As strings in Python are immutable, you can call methods on them without modifying the original strings. Let’s get started.

Python split() Method Syntax

When you need to split a string into substrings, you can use the split() method.

The split() method acts on a string and returns a list of substrings. The syntax is:

  • is any valid Python string,
  • sep is the separator that you’d like to split on. It should be specified as a string.
  • sep is an optional argument. By default, this method splits strings on whitespaces.
  • maxsplit is an optional argument indicating the number of times you’d like to split .
  • maxsplit has a default value of -1 , which splits the string on all occurrences of sep .

And setting maxsplit = 1 will leave you with two chunks – one with the section of before the first comma, and another with the section of after the first comma.

When you split a string once, you’ll get 2 chunks. When you split a string twice, you’ll get 3 chunks. When you split a string k times, you’ll get k+1 chunks.

▶ Let’s take a few examples to see the split() method in action.

Python split() Method Examples

Let’s start with my_string shown below.

my_string = "I code for 2 hours everyday"

Now, call the split() method on my_string , without the arguments sep and maxsplit .

image-50

You can see that my_string has been split on all whitespaces and the list of substrings is returned, as shown above.

▶ Let’s now consider the following example. Here, my_string has names of fruits, separated by commas.

my_string = "Apples,Oranges,Pears,Bananas,Berries"

Let’s now split my_string on commas – set sep = «,» or only specify «,» in the method call.

As expected, the split() method returns a list of fruits, where each fruit in my_string is now a list item.

image-51

▶ Let’s now use the optional maxsplit argument as well by setting it equal to 2.

image-52

Let’s try to parse the returned list.

Recall that my_string is «Apples,Oranges,Pears,Bananas,Berries» , and we decided to split on commas ( «,» ).

  • The first comma is after Apples , and after the first split you’ll have 2 items, Apples and Oranges,Pears,Bananas,Berries .
  • The second comma is after Oranges . And you’ll have 3 items, Apples , Oranges , and Pears,Bananas,Berries after the second split.
  • At this point, you’ve reached the maxsplit count of 2, and no further splits can be made.
  • This is why the portion of the string after the second comma is lumped together as a single item in the returned list.

I hope you understand how the split() method and the arguments sep and maxsplit work.

Python join() Method Syntax

Now that you know how to split a string into substrings, it’s time to learn how to use the join() method to form a string from substrings.

The syntax of Python’s join() method is:

  • is any Python iterable containing the substrings, say, a list or a tuple, and
  • is the separator that you’d like to join the substrings on.

▶ And it’s time for examples.

Python join() Method Examples

In the previous section on the split() method, you split my_string into a list on the occurrences of commas. Let’s call the list my_list .

Now, you’ll form a string using the join() method to put together items in the returned list. The items in my_list are all names of fruits.

my_list = my_string.split(",") # after my_string is split my_list is: ['Apples', 'Oranges', 'Pears', 'Bananas', 'Berries'] 

📑 Note that the separator to join on should be specified as a string. You’ll run into syntax errors if you don’t do so, as shown below.

image-49

▶ To join the items in my_list using a comma as the separator, use «,» not , . This is shown in the code snippet below.

The above line of code joins items in my_list using a comma followed by a space as the separator.

image-53

You can specify any separator of your choice. This time, you’ll use 3 underscores ( ___ ) to join items in my_list .

image-54

The items in my_list have now been joined into a single string, and have all been separated from each other by a ___ .

And you now know how you can form a Python string by putting together substrings using the join() method.

Conclusion

In this tutorial, you’ve learned the following:

  • .split(sep, maxsplit) splits on the occurrence of sep , maxsplit number of times,
  • .join() joins substrings in using as the separator.

Hope you found this tutorial helpful. Happy coding!

Источник

Split and join in python

Методы join() и split() в Python: преобразование списка и строки

Методы join() и split() в Python: преобразование списка и строки

В языке программирования Python существует множество методов для работы со строками и списками. В данной статье мы рассмотрим два метода: join() , который используется для преобразования списка в строку и метод split() , который преобразует строку в список. Также мы рассмотрим примеры использования этих методов.

Метод join() для преобразования списка в строку

Метод join() позволяет объединить элементы списка в одну строку. Синтаксис метода выглядит следующим образом:

Здесь str — это разделитель, который будет использован для объединения элементов списка. iterable — это список элементов, которые будут объединены в строку.

Рассмотрим пример:

words = ['Hello', 'world', '!'] result = ' '.join(words) print(result) # Hello world ! 

В данном примере мы создаем список words , который содержит три строки. Затем мы используем метод join() для объединения элементов списка в одну строку, разделяя элементы пробелами. Результатом будет строка Hello world ! .

Метод split() для преобразования строки в список

Метод split() используется для преобразования строки в список.

Синтаксис метода выглядит следующим образом:

str.split(separator, maxsplit) 

Здесь separator — это разделитель, который будет использован для разделения строки на элементы списка. По умолчанию используется пробел. maxsplit — это максимальное количество разделений, которые могут быть выполнены. По умолчанию это значение равно -1 , что означает, что все возможные разделения будут выполнены.

Рассмотрим пример:

sentence = 'Hello world!' result = sentence.split() print(result) # ['Hello', 'world!'] 

В данном примере мы создаем строку sentence , содержащую две слова, разделенные пробелом. Затем мы используем метод split() для разделения строки на элементы списка. Результатом будет список [‘Hello’, ‘world!’] .

Примеры использования метода join() в Python

Рассмотрим еще несколько примеров использования метода join() .

# Пример 1 numbers = [1, 2, 3, 4, 5] result = '-'.join(map(str, numbers)) print(result) # Вывод: '1-2-3-4-5'  # Пример 2 names = ['Alice', 'Bob', 'Charlie'] result = ', '.join(names) print(result) # Вывод: 'Alice, Bob, Charlie'  # Пример 3 text = 'The quick brown fox jumps over the lazy dog' result = text.split() result.reverse() result = ' '.join(result) print(result) # Вывод: 'dog lazy the over jumps fox brown quick The' 

Примеры использования метода split() в Python

Рассмотрим еще несколько примеров использования метода split() .

# Пример 1 - Разделение строки на слова text = "Hello, world!" words = text.split() print(words) # Вывод: ['Hello,', 'world!']  # Пример 2 - Разделение строки на части с помощью специального разделителя path = "/home/user/Documents/myfile.txt" parts = path.split("/") print(parts) # Вывод: ['', 'home', 'user', 'Documents', 'myfile.txt']  # Пример 3 - Разделение строки на ключ и значение по разделителю = config = "debug=True" key, value = config.split("=") print(key) # Вывод: 'debug' print(value) # Вывод: 'True' 

Заключение

В заключение, методы join() и split() в Python являются очень полезными и часто используемыми при работе со строками и списками. Метод join() позволяет объединить список строк в одну строку с заданным разделителем, в то время как метод split() позволяет разделить строку на части по заданному разделителю и получить список этих частей.

Эти методы просты в использовании и могут быть очень полезными при работе с текстовыми данными и форматировании вывода информации. Важно помнить, что метод join() работает только со списками строк, а метод split() возвращает список строк, полученный путем разделения исходной строки.

Надеюсь, эта статья помогла вам лучше понять эти методы и их применение в Python.

Источник

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