Как разделить числа в строке python
Перейти к содержимому

Как разделить числа в строке python

  • автор:

How to split a string of space separated numbers into integers?

I have a string «42 0» (for example) and need to get an array of the two integers. Can I do a .split on a space?

martineau's user avatar

9 Answers 9

Note that str.split(» «) is identical in this case, but would behave differently if there were more than one space in a row. As well, .split() splits on all whitespace, not just spaces.

Using map usually looks cleaner than using list comprehensions when you want to convert the items of iterables to built-ins like int , float , str , etc. In Python 2:

In Python 3, map will return a lazy object. You can get it into a list with list() :

Python String split () Пример

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

Метод split обычно помогает решить задачу разбивки строк на более мелкие фрагменты на основе определенных строк. У вас может быть длинная строка, сгруппированная по определенному символу, и вы хотите разбить строку на основе этого символа. Вот где метод split вступает в игру.

1.1 Синтаксис

Метод split является частью класса String в Python.

S.split (разделитель, maxsplit) -> Список строк

Первое, что вам нужно, это строка, которую вы хотите разделить. Затем строка, которую вы хотите использовать в качестве разделителя. Если разделитель или None не пропущены, пробел предполагается в качестве разделителя. Затем параметр maxsplit используется для определения количества делений. По умолчанию он разделяется на максимально возможное количество строк на основе разделителя.

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

2. Примеры

Теперь давайте рассмотрим некоторые примеры метода, split на части.

2.1 Python String split () Пример 1

Представьте, что у вас есть строка «Что мы делаем сейчас» . Эта строка представлена ​​в памяти следующим образом:

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:

Let’s break it down:

  • 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:

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?

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, . :

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:

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:

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:

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.

Разделить целое число на цифры в Python

Разделить целое число на цифры в Python

В этом руководстве будут рассмотрены различные методы разделения целого числа на цифры в Python.

Использование понимания списка для разделения целого числа на цифры в Python

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

В этом методе функции str() и int() также используются вместе с пониманием списка для разделения целого числа на цифры. Функции str() и int() используются для преобразования числа в строку, а затем в целое число соответственно.

Следующий код использует понимание списка для разделения целого числа на цифры в Python.

Число num сначала преобразуется в строку с помощью str() в приведенном выше коде. Затем используется составление списка, при котором строка разбивается на отдельные цифры. Наконец, цифры конвертируются обратно в целое число с помощью функции int() .

Используйте функции math.ceil() и math.log() для разделения целого числа на цифры в Python

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

Функция math.ceil() округляет число до целого. Функция math.log() вычисляет натуральный логарифм числа. Чтобы использовать обе эти функции, мы должны импортировать math библиотеку.

Модуль math можно определить как всегда доступный и стандартный модуль в Python. Он обеспечивает доступ к основным функциям библиотеки C.

В следующем коде используются функции понимания списка, math.ceil() и math.log() для разделения целого числа на цифры в Python.

Используйте функции map() и str.split() для разделения целого числа на цифры в Python

Функция map() реализует указанную функцию для каждого элемента в итерации. Затем элемент передается в качестве параметра функции.

Метод split() , как следует из названия, используется для разделения строки на список. Он имеет базовый синтаксис и содержит два параметра: separator и maxsplit .

Число должно быть уже в строковом формате, чтобы можно было использовать этот метод.

В следующем коде используются функции map() и str.split() для разделения целого числа на цифры в Python.

Здесь мы использовали метод str.split() для разделения заданного числа в строковом формате на список строк, содержащих каждое число. Затем используется функция map() , которая используется для создания объекта карты, который преобразует каждую строку в целое число. Наконец, list(mapping) используется для создания списка из объекта карты.

Использование цикла for для разделения целого числа на цифры в Python

В этом методе мы используем цикл и выполняем технику нарезки до указанного количества цифр (в данном случае A=1 ), а затем, наконец, используем функцию int() для преобразования в целое число.

Следующий код использует int() + цикл + срез для разделения целого числа на цифры в Python.

Vaibhhav is an IT professional who has a strong-hold in Python programming and various projects under his belt. He has an eagerness to discover new things and is a quick learner.

Добавить комментарий

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