Как разбить строку на слова в python

от admin

Learn How To Use Split Function In Python

Python programming language has various data types including strings. Even though strings are immutable in nature, we can still manipulate a string using functions like a split function. It breaks down larger strings into smaller strings using different parameters. In this article, we will learn about how we can use the split function in python. Following are the topics discussed in this article:

  • What Is A String?
  • Need For Split Function?
  • How To Use Split Function In Python?
  • Split Parameters
  • Separator
  • Max
  • Example

What Is A String?

Strings in python represent unicode character values. Python does not have a character data type, a single character is also considered as a string.

We use the single or double quotes to declare a string. To access a string, we use the indexes and square brackets. Since strings are mutable in nature, we cannot make any changes after declaring a string.

Although we cannot change a string after declaration, we can split a string in python.

Need For Split Function

Split function returns a list of strings after dividing the string based on the given separator. Following are the advantages of using a split function in python:

  • At some point we may have to break down a large string into smaller chunks or strings.
  • It is the opposite of concatenation, which adds two strings together.
  • The white spaces are considered as a separator if none is provided in the split function.
  • It becomes easier to analyze and deduct conclusions.
  • It helps to decode encrypted strings.

How To Use Split Function In Python?

Split function breaks down a larger string and gives a list with smaller chunks or strings. Below is an example to split a string in python.

Above is a simple example to show how split function can be used to break down the whole text into smaller strings. But split function has different parameters to optimize the execution.

Split Parameters

  1. Separator — It acts like a delimiter, the string is broken down according to the separator specified. It is optional as well, if there is no separator specified, the default separator will be the white space.
  2. Max — It is optional as well. It defines the number of splits that will take place. The default value is -1 which means no limits on the number of splits.

Separator

Below is an example to show the split function with a separator parameter:

In the above example, the separator is specified according to which the string is split into smaller strings.

Below is an example to show the split function with a max parameter:

The max parameter in the above example is set to 3, which means the output will have 4 elements in the list of strings.

Example

Below are a few examples, where we can use the split function to split the string into smaller chunks or strings.

In this blog, we have learnt how split function can be used to break down large strings into smaller chunks or strings. String is an immutable data structure which means it cannot be changed once you have declared it. Although manipulation can be done using split function. Python programming language has different data types like list, dictionary, tuple, set etc.

Primitive data types and specialized data structures optimize your code and gives an edge to python over other programming languages. To master your skills enroll to Python online training program and kick-start your learning.

If you wish to check out more articles on the market’s most trending technologies like Artificial Intelligence, DevOps, Ethical Hacking, then you can refer to Edureka’s official site.

Do look out for other articles in this series which will explain the various other aspects of Python and Data Science.

How do I split a string into a list of words?

How do I split a sentence and store each word in a list? For example, given a string like "these are words" , how do I get a list like ["these", "are", "words"] ?

9 Answers 9

Given a string sentence , this stores each word in a list called words :

To split the string text on any consecutive runs of whitespace:

To split the string text on a custom delimiter such as "," :

The words variable will be a list and contain the words from text split on the delimiter.

Mateen Ulhaq's user avatar

Return a list of the words in the string, using sep as the delimiter . If sep is not specified or is None , a different splitting algorithm is applied: runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Depending on what you plan to do with your sentence-as-a-list, you may want to look at the Natural Language Took Kit. It deals heavily with text processing and evaluation. You can also use it to solve your problem:

This has the added benefit of splitting out punctuation.

This allows you to filter out any punctuation you don’t want and use only words.

Читать:
Белый экран на ноутбуке lenovo что делать

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.

Как использовать Split в Python

Метод Split() в Python возвращает список слов в строке / строке, разделенных строкой разделителя.

Разбиение строки Split

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

Разделение на первое вхождение

В следующем примере он будет разделен только на 2 пробела.

Разделение строк из текстового файла в Python

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

Похожие статьи