How to parse string in python

How to split and parse a string in Python?

In this python tutorial, we will see how to split and parse a string in Python.

Table Of Contents

Split and parse a string using split()

In Python, string class provides a function split(), to break the string into a list of substrings. It splits the string based on few optional arguments i.e.

  • sep : A delimiter. By default, the delimiter is a whitespace.
  • maxsplit : The maximum number of splits it will do. Default value for maxsplit is -1, which means no limit.

We can use this to split a string into list of words. Let’s see an examples,

Example 1: Split a string by using space as the delimiter string

Here we will consider the string – “Welcome to thisPointer” and split it into words by using a whitespace as a delimeter.

Читайте также:  Python search list of objects

Frequently Asked:

strValue = "Welcome to thisPointer" print(strValue) # Split the string listOfWords = strValue.split() print(listOfWords)
Welcome to thisPointer ['Welcome', 'to', 'thisPointer']

The above string is split into three words.

Example 2: Split a string by using comma as the delimiter string

here, we will provide a custom separator to the split() function i.e. a comma. It will split the string based on it. Let’s see an example,

strValue = "Welcome,to,this,Pointer" print(strValue) # Split the string by using comma as separator listOfWords = strValue.split(sep=',') print(listOfWords)
Welcome,to,this,Pointer ['Welcome', 'to', 'this', 'Pointer']

Example 3: Split a string by a character in Python

We can pass any character as the separator in the split() function. Let’s see an example, where we will pass character ‘o’ as the separator.

strValue = "Welcome to this Pointer" print(strValue) # Split the string by using letter 'o' as delimeter listOfWords = strValue.split(sep='o') print(listOfWords)
Welcome to this Pointer ['Welc', 'me t', ' this P', 'inter']

Example 3: Split a string into two substrings in Python

By default, the split() function splits a string into all possible substrings. But what if we are interested in only few substrings? For example, by default the split() function will break the string “Welcome to this Pointer” into four substrings. If we want it to break the string into two substrings only, then we can pass the value of maxsplit as 1 in the split() function. Let’s see an example,

strValue = "Welcome to this Pointer" print(strValue) # Split the string into two substrings listOfSubstrings = strValue.split(maxsplit=1) print(listOfSubstrings)
Welcome to this Pointer ['Welcome', 'to this Pointer']

It broke the string into a list of substrings by using space as a delimeter, and returned only two substrings.

Summary

We learned how to split and parse a string using split() function in Python.

Share your love

Leave a Comment Cancel Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Terms of Use

Disclaimer

Copyright © 2023 thisPointer

To provide the best experiences, we and our partners use technologies like cookies to store and/or access device information. Consenting to these technologies will allow us and our partners to process personal data such as browsing behavior or unique IDs on this site and show (non-) personalized ads. Not consenting or withdrawing consent, may adversely affect certain features and functions.

Click below to consent to the above or make granular choices. Your choices will be applied to this site only. You can change your settings at any time, including withdrawing your consent, by using the toggles on the Cookie Policy, or by clicking on the manage consent button at the bottom of the screen.

The technical storage or access is strictly necessary for the legitimate purpose of enabling the use of a specific service explicitly requested by the subscriber or user, or for the sole purpose of carrying out the transmission of a communication over an electronic communications network.

The technical storage or access is necessary for the legitimate purpose of storing preferences that are not requested by the subscriber or user.

The technical storage or access that is used exclusively for statistical purposes. The technical storage or access that is used exclusively for anonymous statistical purposes. Without a subpoena, voluntary compliance on the part of your Internet Service Provider, or additional records from a third party, information stored or retrieved for this purpose alone cannot usually be used to identify you.

The technical storage or access is required to create user profiles to send advertising, or to track the user on a website or across several websites for similar marketing purposes.

Источник

How to Parse a String in Python – Parsing Strings Explained

Ihechikara Vincent Abba

Ihechikara Vincent Abba

How to Parse a String in Python – Parsing Strings Explained

Parsing a string can mean different things in Python. You can parse a string by splitting or extracting the substrings.

You can also parse a string by converting it to an integer or float variable. Although this should be categorized as a type conversion operation, you’ll come across resources that refer to it as string parsing.

In this article, you’ll learn how to parse a string using the split() and strip() methods. You’ll also learn how to convert a string to an integer using the int() function.

How To Parse a String in Python Using the split() Method

You can use the split() method in Python to «split» substrings of a string into a list.

Here’s what the parameter looks like:

string.split(separator, maxsplit)

The split() method has two optional parameters:

  • separator specifies where to start splitting from (you’ll understand this better with the examples in the next section).
  • maxsplit specifies the maximum number of splits.

split() Method Example #1 — How To Use the Separator Parameter

favorite_languages = "JavaScript, Python, and Java" lang_split = favorite_languages.split(",") print(lang_split) # ['JavaScript', ' Python', ' and Java'] 

In the example above, we created a string called favorite_languages which had three substrings: «JavaScript, Python, and Java».

Using the split() method, we specified that each substring should be split after each comma in the string: favorite_languages.split(«,») .

The result was a list of each substring: [‘JavaScript’, ‘ Python’, ‘ and Java’].

This example shows how to use the first parameter of the split() method. The next example will help you understand the second parameter.

split() Method Example #2 — How To Use the Maxsplit Parameter

favorite_languages = "JavaScript, Python, and Java" lang_split = favorite_languages.split(",", 1) print(lang_split) # ['JavaScript', ' Python, and Java']

In the code above, we made use of the maxsplit parameter which specifies the number of splits to be performed.

So favorite_languages.split(«,», 1) means that only one substring should be split, while the rest would remain as they were in the original string.

In the output of the code, only JavaScript was split, while Python and Java retained their initial positions in the string. That is: [‘JavaScript’, ‘ Python, and Java’] .

How To Parse a String in Python Using the strip() Method

You can use the strip() method to remove white spaces or specified characters in a string.

Here’s what the syntax looks like:

The chars parameter specifies the set of characters to be removed. This parameter is optional, so leaving the parenthesis empty will only remove white spaces.

strip() Method Example #1

username = " Doe " user = username.strip() print(user) # Doe

In the example above, we had a string with leading and trailing whitespace characters: » Doe «.

Using the strip method without any parameter, we got rid of the whitespaces: username.strip() .

In the next example, we’ll pass in parameters to the strip() method.

strip() Method Example #2

In this section, we’ll use a string that has different characters in it that aren’t whitespaces:

username = "=+---Doe---+ language-python">username = "=+---Doe---+=" user = username.strip("=+-") print(user) # Doe

In the code above, we passed in the characters to be removed from the string as a parameter to the strip() method: username.strip(«=+-«) .

Note that you have to nest those characters in quotation marks («=+-«).

How To Convert a String to an Integer Using the int() Function

Data type conversion helps you perform certain operations that involve incompatible data types.

For instance, the example below shows what happens when you try to add an integer and a string:

age = "300" print(age + 300) # TypeError: can only concatenate str (not "int") to str

In the code above, we created a string value with a value of «300». When we tried adding it to an integer value of 300, we got an error.

The error is thrown because the compiler assumes we’re trying to add two strings. String concatenation in Python cannot be performed using a string and an integer.

To solve this problem, you can convert the string to an integer before using it in a mathematical operation.

Here’s how you can do that using the int() function:

age = "300" age_to_int = int(age) print(age_to_int + 300) # 600

In the code above, we used the int() function to convert the age string to an integer: int(age) .

Now, you’re to use the variable as an integer.

A common use case for converting from a string to an integer is seen when getting input from a user. You can see an example like that in this article.

Summary

In this article, we talked about parsing strings in Python.

We saw examples that showed how to parse a string using the split() and strip() methods.

We also saw how to convert a string to an integer using the int() function.

Happy coding! I also write about Python on my blog.

Источник

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