"2.7.0_bf4fda703454".split("_") gives a list of strings:

In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']

This splits the string at every underscore. If you want it to stop after the first split, use "2.7.0_bf4fda703454".split("_", 1).

If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:

In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)

In [9]: lhs
Out[9]: '2.7.0'

In [10]: rhs
Out[10]: 'bf4fda703454'

An alternative is to use partition(). The usage is similar to the last example, except that it returns three components instead of two. The principal advantage is that this method doesn't fail if the string doesn't contain the separator.

Answer from NPE on Stack Overflow
Top answer
1 of 3
164

"2.7.0_bf4fda703454".split("_") gives a list of strings:

In [1]: "2.7.0_bf4fda703454".split("_")
Out[1]: ['2.7.0', 'bf4fda703454']

This splits the string at every underscore. If you want it to stop after the first split, use "2.7.0_bf4fda703454".split("_", 1).

If you know for a fact that the string contains an underscore, you can even unpack the LHS and RHS into separate variables:

In [8]: lhs, rhs = "2.7.0_bf4fda703454".split("_", 1)

In [9]: lhs
Out[9]: '2.7.0'

In [10]: rhs
Out[10]: 'bf4fda703454'

An alternative is to use partition(). The usage is similar to the last example, except that it returns three components instead of two. The principal advantage is that this method doesn't fail if the string doesn't contain the separator.

2 of 3
103

Python string parsing walkthrough

Split a string on space, get a list, show its type, print it out:

el@apollo:~/foo$ python
>>> mystring = "What does the fox say?"

>>> mylist = mystring.split(" ")

>>> print type(mylist)
<type 'list'>

>>> print mylist
['What', 'does', 'the', 'fox', 'say?']

If you have two delimiters next to each other, empty string is assumed:

el@apollo:~/foo$ python
>>> mystring = "its  so   fluffy   im gonna    DIE!!!"

>>> print mystring.split(" ")
['its', '', 'so', '', '', 'fluffy', '', '', 'im', 'gonna', '', '', '', 'DIE!!!']

Split a string on underscore and grab the 5th item in the list:

el@apollo:~/foo$ python
>>> mystring = "Time_to_fire_up_Kowalski's_Nuclear_reactor."

>>> mystring.split("_")[4]
"Kowalski's"

Collapse multiple spaces into one

el@apollo:~/foo$ python
>>> mystring = 'collapse    these       spaces'

>>> mycollapsedstring = ' '.join(mystring.split())

>>> print mycollapsedstring.split(' ')
['collapse', 'these', 'spaces']

When you pass no parameter to Python's split method, the documentation states: "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".

Hold onto your hats boys, parse on a regular expression:

el@apollo:~/foo$ python
>>> mystring = 'zzzzzzabczzzzzzdefzzzzzzzzzghizzzzzzzzzzzz'
>>> import re
>>> mylist = re.split("[a-m]+", mystring)
>>> print mylist
['zzzzzz', 'zzzzzz', 'zzzzzzzzz', 'zzzzzzzzzzzz']

The regular expression "[a-m]+" means the lowercase letters a through m that occur one or more times are matched as a delimiter. re is a library to be imported.

Or if you want to chomp the items one at a time:

el@apollo:~/foo$ python
>>> mystring = "theres coffee in that nebula"

>>> mytuple = mystring.partition(" ")

>>> print type(mytuple)
<type 'tuple'>

>>> print mytuple
('theres', ' ', 'coffee in that nebula')

>>> print mytuple[0]
theres

>>> print mytuple[2]
coffee in that nebula
๐ŸŒ
GeeksforGeeks
geeksforgeeks.org โ€บ python โ€บ split-and-parse-a-string-in-python
Split and Parse a string in Python - GeeksforGeeks
July 23, 2025 - import re # Given string s = "geeks;for,geeks" # Split `s` at ';', ',', or space res= re.split(r'[;, ]',s) # Parse and print each item for item in res: print(item) ... We can use the map() function to split a string into parts and then change each part, like turning all words into uppercase.
๐ŸŒ
freeCodeCamp
freecodecamp.org โ€บ news โ€บ how-to-parse-a-string-in-python
How to Parse a String in Python โ€“ Parsing Strings Explained
May 4, 2023 - 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.
๐ŸŒ
Python
docs.python.org โ€บ 3 โ€บ library โ€บ string.html
string โ€” Common string operations
If there is no literal text (which ... string. If there is no replacement field, then the values of field_name, format_spec and conversion will be None. The value of field_name is unmodified and auto-numbering of non-numbered positional fields is done by vformat(). ... Given field_name, convert it to an object to be formatted. Auto-numbering of field_name returned from parse() is done ...
๐ŸŒ
GitHub
github.com โ€บ r1chardj0n3s โ€บ parse
GitHub - r1chardj0n3s/parse: Parse strings using a specification based on the Python format() syntax. ยท GitHub
>>> parse('SPAM', 'spam', case_sensitive=True) is None True ยท A basic version of the Format String Syntax is supported with anonymous (fixed-position), named and formatted fields: ... Field names must be a valid Python identifiers, including dotted names; element indexes imply dictionaries (see below for example).
Author: r1chardj0n3s
๐ŸŒ
Nylas
nylas.com โ€บ video tutorials โ€บ to parse or not to parse (a guide to pythonโ€™s parse)
To parse or not to parse (a guide to Pythonโ€™s Parse) | Nylas
June 5, 2024 - from parse import * string = "We need 5 examples of Regex in Python" parse_string = parse('We need {:d} examples of {:w} in {:w}', string) print(f"How many: {parse_string[0]}") print(f"What: {parse_string[1]}") print(f"Language: {parse_string[2]}")
๐ŸŒ
PyPI
pypi.org โ€บ project โ€บ parse
parse
JavaScript is disabled in your browser. Please enable JavaScript to proceed ยท A required part of this site couldnโ€™t load. This may be due to a browser extension, network issues, or browser settings. Please check your connection, disable any ad blockers, or try using a different browser
Find elsewhere
๐ŸŒ
Spark By {Examples}
sparkbyexamples.com โ€บ home โ€บ python โ€บ how to parse a string in python
How to Parse a String in Python - Spark By {Examples}
May 21, 2024 - How to Parse a String in Python? Parsing a string in Python involves extracting specific information or patterns from a given string. Several techniques
๐ŸŒ
Python Central
pythoncentral.io โ€บ how-to-parse-a-string-in-python-a-step-by-step-guide
How To Parse a String in Python: A Step-by-Step Guide | Python Central
February 29, 2024 - You can slice a string by specifying the start and end indices of the string you require. You must place a colon between these indices, and the indices themselves must be within square brackets. ... Did you notice that the extracted substring in the output does not include the character at the ending index? Remember that the character at the last index doesn't get parsed when parsing by index. The slice() function comes built-in with Python and accepts three arguments, of which two are mandatory: the beginning index and the end index of the slice.
๐ŸŒ
Pierian Training
pieriantraining.com โ€บ home โ€บ parsing strings in python: techniques for beginners
Parsing Strings in Python: Techniques for Beginners - Pierian Training
April 28, 2023 - They allow you to define complex patterns that can match various types of characters and substrings within a larger string. 3. Parsing libraries: There are several parsing libraries available in Python that can be used to extract information from structured data formats such as JSON, XML, and CSV files.
๐ŸŒ
Replit
replit.com โ€บ home โ€บ discover โ€บ how to parse a string in python
How to parse a string in Python | Replit
April 14, 2026 - Learn how to parse strings in Python. This guide covers various methods, tips, real-world applications, and how to debug common errors.
๐ŸŒ
Python Guides
pythonguides.com โ€บ parse-a-string-in-python
How To Parse A String In Python?
April 21, 2025 - Learn how to parse a string in Python using techniques like split(), regular expressions, slicing, and libraries like argparse. Includes examples and tips!
๐ŸŒ
Python.org
discuss.python.org โ€บ python help
How do I parse the string? - Python Help - Discussions on Python.org
April 10, 2024 - hello There is a string below. FTP://21.105.28.15/abc/test1.txt Cut this string /abc/ I just want to get the path. How do I parse the string? import pymssql conn = pymssql.connect('10.21.100.21', 'sa', 'abc', 'DBA', as_dict=False) cur = conn.cursor() cur.execute('select path From table') fetch = cur.fetchall() for i in fetch: print (i)
๐ŸŒ
Humboldt
gis.humboldt.edu โ€บ OLM โ€บ old โ€บ Temp โ€บ 03_2_ParsingStrings.html
GIS Programming With Python - Parsing Strings
It's a good idea to use Python's String function "strip()" to remove any unwanted white space. Add the code below to the code you entered from above. ... The last thing you'll need to know about parsing strings is that the "find()" function can take additional parameters including a starting point within the string.
๐ŸŒ
Tomassetti
tomassetti.me โ€บ home โ€บ parsing in python: tools and libraries
Parsing in Python: all the tools and libraries you can use
July 19, 2017 - It now requires Python 3.3 or later, which should only be a problem for people stuck with Python 2. The project now has ample documentation, examples and a tutorial. The following example comes from the documentation and shows how to parse a date. # from the documentation # parsing a date from parsy import string, regex from datetime import date ddmmyy = regex(r'[0-9]{2}').map(int).sep_by(string("-"), min=3, max=3).combine( lambda d, m, y: date(2000 + y, m, d)) ddmmyy.parse('06-05-14')
๐ŸŒ
Konfuzio
konfuzio.com โ€บ start โ€บ blog โ€บ python โ€บ python string parsing tutorial for string to sequence
Python string parsing tutorial for string to sequence
June 4, 2025 - I have already used my knowledge in 2025 to implement a tool that we called Quick Extract. It also helps beginners to create a simple Document API with a few sample documents in order to parse new documents. ... In Python, a String a sequence of characters. These characters can be accessed via an index, which is used for 0 begins.
๐ŸŒ
Quora
quora.com โ€บ How-do-I-parse-a-string-in-Python
How to parse a string in Python - Quora
Answer (1 of 2): Parsing in general refers to the process of interpreting a text represented in a certain language. If that language is Python you can use the built-in eval() function to parse the string. If you know the text represents a integer you can use the int() function; if it is a float y...
๐ŸŒ
Vipinajayakumar
vipinajayakumar.com โ€บ parsing-text-with-python
Parsing text with Python ยท vipinajayakumar
A Python specific extension allows us to name the groups and refer to them by their name instead. We can specify a name within a parenthesized group (...) like so: (?P<name>...). Let us first define all the regular expressions. Be sure to use raw strings for regex, i.e., use the subscript r before each pattern. Then, we can define a function that checks for regex matches. Finally, for the main event, we have the file parser function.