Python split string пример

Строковые методы split() и join() в Python

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

Важно отметить, что поскольку строки в Python неизменяемы, вы можете вызывать для них методы, не изменяя исходные строки. Итак, давайте начнем!

Метод split()

Когда вам нужно разбить строку на подстроки, вы можете использовать метод split().

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

Здесь – любая допустимая строка в Python, а sep – это разделитель, по которому вы хотите разделить исходную строку. Его следует указывать в виде строки.

Например, если вы хотите разделить по запятым, нужно установить sep = «,» .

sep – необязательный аргумент. По умолчанию метод split() разбивает строки по пробелам.

Читайте также:  Formatting echo in php

maxsplit – еще один опциональный аргумент, указывающий, сколько раз вы хотите разделить исходную строку . По умолчанию maxsplit имеет значение -1. При таком значении метод разбивает строку по всем вхождениям параметра sep.

Если вы хотите разделить исходную строку на две части, по первому вхождению запятой, вы можете установить maxsplit = 1 . Так вы получите две подстроки: части исходной строки до и после первой запятой.

Таким образом, при одном разрезе строки вы получаете 2 подстроки. При двух разрезах — 3 подстроки. то есть, разрезая строку k раз, вы получите k+1 фрагментов.

Давайте рассмотрим несколько примеров, чтобы увидеть метод split() в действии.

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

Зададим строку my_string , как это показанного ниже. После этого вызовем метод split() для my_string без аргументов sep и maxsplit .

my_string = "I code for 2 hours everyday" my_string.split() # ['I', 'code', 'for', '2', 'hours', 'everyday']

Вы можете видеть, что my_string разделена по всем пробелам. Метод возвращает список подстрок.

Рассмотрим следующий пример. Здесь my_string содержит названия фруктов, разделенные запятыми.

Давайте разделим my_string по запятым. Для этого нужно установить sep = «,» или просто передать в метод «,» при вызове.

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

Как и ожидалось, метод split() вернул список фруктов, где каждый фрукт из my_string стал элементом списка.

Теперь давайте воспользуемся необязательным аргументом maxsplit и установив его равным 2.

my_string.split(",", 2) # ['Apples', 'Oranges', 'Pears,Bananas,Berries']

Попробуем разобрать получившийся список.

Напомним, что my_string = «Apples,Oranges,Pears,Bananas,Berries» , и мы решили разделить эту строку по запятым «,» .

Первая запятая стоит после Apples , и после первого разделения у нас будет две подстроки: Apples и Oranges,Pears,Bananas,Berries .

Вторая запятая стоит после Oranges . Таким образом, после второго деления у нас будет уже три подстроки: Apples , Oranges и Pears,Bananas,Berries .

Сделав два разреза строки, мы достигли установленного максимума, и дальнейшее деление невозможно. Поэтому часть строки после второй запятой объединяется в один элемент в возвращаемом списке.

Надеюсь, теперь вы понимаете, как работает метод split() и для чего нужны аргументы sep и maxsplit .

Метод join()

Теперь, когда вы знаете, как разбить строку на подстроки, пора научиться использовать метод join() для формирования строки из подстрок.

Синтаксис метода Python join() следующий:

Здесь – любой итерируемый объект Python, содержащий подстроки. Это может быть, например, список или кортеж. – это разделитель, с помощью которого вы хотите объединить подстроки.

По сути, метод join() объединяет все элементы в , используя в качестве разделителя.

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

В предыдущем разделе мы разбивали строку my_string по запятым и получали в итоге список подстрок. Назовем этот список my_list .

Теперь давайте сформируем строку, объединив элементы этого списка при помощи метода join(). Все элементы в my_list – это названия фруктов.

my_list = my_string.split(",") # после разделения my_string мы получаем my_list: # ['Apples', 'Oranges', 'Pears', 'Bananas', 'Berries']

Обратите внимание, что разделитель для присоединения должен быть указан именно в виде строки. В противном случае вы столкнетесь с синтаксическими ошибками.

Чтобы объединить элементы в my_list с использованием запятой в качестве разделителя, используйте «,» а не просто , . Это показано во фрагменте кода ниже.

", ".join(my_list) # Output: Apples, Oranges, Pears, Bananas, Berries

Здесь элементы my_list объединяются в одну строку с помощью запятых, за которыми следуют пробелы.

Разделитель может быть любым.

Давайте для примера используем в качестве разделителя 3 символа подчеркивания ___ .

"___".join(my_list) # Output: Apples___Oranges___Pears___Bananas___Berries

Элементы в my_list теперь объединены в одну строку и отделены друг от друга тремя подчеркиваниями ___ .

Теперь вы знаете, как сформировать одну строку из нескольких подстрок с помощью метода join().

Заключение

Итак, мы рассмотрели строковые методы split() и join(). Из этой статьи вы узнали следующее:

  • .split (sep, maxsplit) разбивает исходную строку по вхождениям разделителя sep , maxsplit раз.
  • .join() объединяет подстроки в итерируемый объект , используя в качестве разделителя.

Надеюсь, вам была полезна данная статья. Успехов в написании кода!

Более 50 задач на строки в нашем телеграм канале Python Turbo. Уютное сообщество Python разработчиков.

Источник

Python .split() – Splitting a String in Python

Dionysia Lemonaki

Dionysia Lemonaki

Python .split() – Splitting a String in Python

In this article, you will learn how to split a string in Python.

Firstly, I’ll introduce you to the syntax of the .split() method. After that, you will see how to use the .split() method with and without arguments, using code examples along the way.

Here is what we will cover:

What Is The .split() Method in Python? .split() Method Syntax Breakdown

You use the .split() method for splitting a string into a list.

The general syntax for the .split() method looks something like the following:

string.split(separator, maxsplit) 
  • string is the string you want to split. This is the string on which you call the .split() method.
  • The .split() method accepts two arguments.
  • The first optional argument is separator , which specifies what kind of separator to use for splitting the string. If this argument is not provided, the default value is any whitespace, meaning the string will split whenever .split() encounters any whitespace.
  • The second optional argument is maxsplit , which specifies the maximum number of splits the .split() method should perform. If this argument is not provided, the default value is -1 , meaning there is no limit on the number of splits, and .split() should split the string on all the occurrences it encounters separator .

The .split() method returns a new list of substrings, and the original string is not modified in any way.

How Does The .split() Method Work Without Any Arguments?

Here is how you would split a string into a list using the .split() method without any arguments:

coding_journey = "I am learning to code for free with freeCodecamp!" # split string into a list and save result into a new variable coding_journey_split = coding_journey.split() print(coding_journey) print(coding_journey_split) # check the data type of coding_journey_split by using the type() function print(type(coding_journey_split)) # output # I am learning to code for free with freeCodecamp! # ['I', 'am', 'learning', 'to', 'code', 'for', 'free', 'with', 'freeCodecamp!'] #

The output shows that each word that makes up the string is now a list item, and the original string is preserved.

When you don’t pass either of the two arguments that the .split() method accepts, then by default, it will split the string every time it encounters whitespace until the string comes to an end.

What happens when you don’t pass any arguments to the .split() method, and it encounters consecutive whitespaces instead of just one?

coding_journey = "I love coding" coding_journey_split = coding_journey.split() print(coding_journey_split) # output # ['I', 'love', 'coding'] 

In the example above, I added consecutive whitespaces between the word love and the word coding . When this is the case, the .split() method treats any consecutive spaces as if they are one single whitespace.

How Does The .split() Method Work With The separator Argument?

As you saw earlier, when there is no separator argument, the default value for it is whitespace. That said, you can set a different separator .

The separator will break and divide the string whenever it encounters the character you specify and will return a list of substrings.

For example, you could make it so that a string splits whenever the .split() method encounters a dot, . :

fave_website = "www.freecodecamp.org" fave_website_split = fave_website.split(".") print(fave_website_split) # output # ['www', 'freecodecamp', 'org'] 

In the example above, the string splits whenever .split() encounters a .

Keep in mind that I didn’t specify a dot followed by a space. That wouldn’t work since the string doesn’t contain a dot followed by a space:

fave_website = "www.freecodecamp.org" fave_website_split = fave_website.split(". ") print(fave_website_split) # output # ['www.freecodecamp.org'] 

Now, let’s revisit the last example from the previous section.

When there was no separator argument, consecutive whitespaces were treated as if they were single whitespace.

However, when you specify a single space as the separator , then the string splits every time it encounters a single space character:

coding_journey = "I love coding" coding_journey_split = coding_journey.split(" ") print(coding_journey_split) # output # ['I', 'love', '', '', 'coding'] 

In the example above, each time .split() encountered a space character, it split the word and added the empty space as a list item.

How Does The .split() Method Work With The maxsplit Argument?

When there is no maxsplit argument, there is no specified limit for when the splitting should stop.

In the first example of the previous section, .split() split the string each and every time it encountered the separator until it reached the end of the string.

However, you can specify when you want the split to end.

For example, you could specify that the split ends after it encounters one dot:

fave_website = "www.freecodecamp.org" fave_website_split = fave_website.split(".", 1) print(fave_website_split) # output # ['www', 'freecodecamp.org'] 

In the example above, I set the maxsplit to 1 , and a list was created with two list items.

I specified that the list should split when it encounters one dot. Once it encountered one dot, the operation would end, and the rest of the string would be a list item on its own.

Conclusion

And there you have it! You now know how to split a string in Python using the .split() method.

I hope you found this tutorial helpful.

To learn more about the Python programming language, check out freeCodeCamp’s Python certification.

You’ll start from the basics and learn in an interactive and beginner-friendly way. You’ll also build five projects at the end to put into practice and help reinforce what you’ve learned.

Thank you for reading, and happy coding!

Источник

Python String split() Method

Split a string into a list where each word is a list item:

txt = «welcome to the jungle»

Definition and Usage

The split() method splits a string into a list.

You can specify the separator, default separator is any whitespace.

Note: When maxsplit is specified, the list will contain the specified number of elements plus one.

Syntax

Parameter Values

Parameter Description
separator Optional. Specifies the separator to use when splitting the string. By default any whitespace is a separator
maxsplit Optional. Specifies how many splits to do. Default value is -1, which is «all occurrences»

More Examples

Example

Split the string, using comma, followed by a space, as a separator:

txt = «hello, my name is Peter, I am 26 years old»

Example

Use a hash character as a separator:

Example

Split the string into a list with max 2 items:

# setting the maxsplit parameter to 1, will return a list with 2 elements!
x = txt.split(«#», 1)

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.

Источник

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