Python String | split()

When working with strings in Python, you might need to part a string into substrings. Or on the other hand you may have to consolidate more modest lumps to shape a string. Python’s parted() and join() string strategies assist you with doing these errands without any problem. In this instructional exercise, you’ll find out with regards to the split() and join() string strategies with a lot of model code.

As strings in Python are changeless, you can call strategies on them without adjusting the first strings. How about we get everything rolling.

The split() technique in Python returns a rundown of the words in the string/line , isolated by the delimiter string. This strategy will return at least one new strings. All substrings are returned in the rundown datatype.

Parameter Description
separator The is a delimiter. The string splits at this specified separator. If is not provided then any white space is a separator.
maxsplit It is a number, which tells us to split the string into maximum of provided number of times. If it is not provided then there is no limit.
return The split() breaks the string at the separator and returns a list of strings.

In case no separator is characterized when you call upon the capacity, whitespace will be utilized as a matter of course. In less difficult terms, the separator is a characterized character that will be set between every factor. The conduct of split on a vacant string relies upon the worth of sep. Assuming sep isn’t determined, or indicated as None, the outcome will be an unfilled rundown. Assuming sep is determined as any string, the outcome will be a rundown containing one component which is an unfilled string .

Splitting lines from a text file in Python

The following Python program reading a text file and splitting it into single words in python

example

Splitting String by newline(\n)

output

Splitting String by tab(\t)

output

Splitting String by comma(,)

output

Syntax

string.split(separator, maxsplit)

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”

x = txt.split(“, “)

print(x)

Example

Use a hash character as a separator:

txt = “apple#banana#cherry#orange”

x = txt.split(“#”)

print(x)

Example

Split the string into a list with max 2 items:

txt = “apple#banana#cherry#orange”

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

print(x)

Leave a Reply

Your email address will not be published. Required fields are marked *