How to split string python
How to split string python
How to Split String in Python?
Python Split String
To split a String in Python using delimiter, you can use split() method of the String Class on this string.
In this tutorial, we shall learn how to split a string in Python, with well detailed Python example programs.
Syntax
The syntax of String.split() method is
Example 1: Split String
In this example, we take a string that has chunks separated by comma. We will split this string using comma as separator and store the result in a variable.
Python Program
Output
Example 2: Split String with limited number of splits
In this example, we take a string that has chunks separated by comma. We will split this string using comma as separator and maximum number of chunks as 3.
Python Program
Output
The string is split thrice and hence 4 chunks.
Example 3: Split String with no arguments
When no arguments are provided to split() function, one ore more spaces are considered as delimiters and the input string is split.
In this example, we will split a string arbitrary number of spaces in between the chunks.
Python Program
Output
Summary
In this tutorial of Python Examples, we have gone through different scenarios where we split the string with different types of delimiters, controlled the number of splits, etc.
Splitting strings in python
I have a string which is like this:
this is [bracket test] «and quotes test «
I’m trying to write something in Python to split it up by space while ignoring spaces within square braces and quotes. The result I’m looking for is:
[‘this’,’is’,’bracket test’,’and quotes test ‘]
6 Answers 6
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Here’s a simplistic solution that works with your test input:
This will return any code that matches either
This works with your example, but might fail for many real-world strings you may encounter. For example, you didn’t say what you expect with unbalanced brackets or quotes,or how you want single quotes or escape characters to work. For simple cases, though, the above might be good enough.
To complete Bryan post and match exactly the answer :
Don’t misunderstand the whole syntax used : This is not several statments on a single line but a single functional statment (more bugproof).
Here’s a simplistic parser (tested against your example input) that introduces the State design pattern.
In real world, you probably want to build a real parser using something like PLY.
Here’s a more procedural approach:
Well, I’ve encountered this problem quite a few times, which led me to write my own system for parsing any kind of syntax.
The result of this can be found here; note that this may be overkill, and it will provide you with something that lets you parse statements with both brackets and parentheses, single and double quotes, as nested as you want. For example, you could parse something like this (example written in Common Lisp):
You can use nesting, brackets (square) and parentheses (round), single- and double-quoted strings, and it’s very extensible.
The idea is basically a configurable implementation of a Finite State Machine which builds up an abstract syntax tree character-by-character. I recommend you look at the source code (see link above), so that you can get an idea of how to do it. It’s capable via regular expressions, but try writing a system using REs and then trying to extend it (or even understand it) later.
How to split a string in Python?
I have read the documentation but don’t fully understand how to do it.
I understand that I need to have some kind of identifier in the string so that the functions can find where to split the string (unless I can target the first space in the sentence?).
The strings are retrieved from a database (if this does matter).
2 Answers 2
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Use the split method on strings:
How it works:
Of course you can also store the substrings in separate variables instead of a list:
But do note that this will cause trouble if certain inputs do not contain spaces:
Examples: «Sico87 is an awful python developer».partition(‘ ‘) returns [«Sico87″,» «,»is an awful python developer»]
«Sico87 is an awful python developer».partition(‘ ‘)[0] returns «Sico87»
An alternative, trickier way is to use split(‘ ‘,1) which works similiarly but returns a variable number of items. It will return a tuple of one or two items, the first item being the first word up until the delimiter and the second being the rest of the string (if there is any).
How do I split a string into a list of characters?
How do I split a string into a list of characters? str.split does not work.
14 Answers 14
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
Use the list constructor:
You take the string and pass it to list()
You can also do it in this very simple way without list():
If you want to process your String one character at a time. you have various options.
Using List comprehension:
Calling Built in list function:
If you just need an array of chars:
If you want to split the str by a particular delimiter:
I explored another two ways to accomplish this task. It may be helpful for someone.
The first one is easy:
And the second one use map and lambda function. It may be appropriate for more complex tasks:
See python docs for more methods
The task boils down to iterating over characters of the string and collecting them into a list. The most naïve solution would look like
Of course, it can be shortened to just
but there still are shorter solutions that do the same thing.
list constructor can be used to convert any iterable (iterators, lists, tuples, string etc.) to list.
The big plus is that it works the same in both Python 2 and Python 3.
Also, starting from Python 3.5 (thanks to the awesome PEP 448) it’s now possible to build a list from any iterable by unpacking it to an empty list literal:
This is neater, and in some cases more efficient than calling list constructor directly.
In Python, how do I split a string and keep the separators?
Here’s the simplest way to explain this. Here’s what I’m using:
Here’s what I want:
The reason is that I want to split a string into tokens, manipulate it, then put it back together again.
17 Answers 17
Trending sort
Trending sort is based off of the default sorting method — by highest score — but it boosts votes that have happened recently, helping to surface more up-to-date answers.
It falls back to sorting by highest score if no posts are trending.
Switch to Trending sort
(Not a general solution, but adding this here in case someone comes here not realizing this method existed.)
another example, split on non alpha-numeric and keep the separators
If you have only 1 separator, you can employ list comprehensions:
Separator as it’s own element:
Another no-regex solution that works well on Python 3
One Lazy and Simple Solution
Assume your regex pattern is split_pattern = r'(!|\?)’
First, you add some same character as the new separator, like ‘[cut]’
new_string = re.sub(split_pattern, ‘\\1[cut]’, your_string)
Then you split the new separator, new_string.split(‘[cut]’)
You can also split a string with an array of strings instead of a regular expression, like this:
replace all seperator: (\W) with seperator + new_seperator: (\W;)
split by the new_seperator: (;)
This is an answer for Python split() without removing the delimiter, so not exactly what the original post asks but the other question was closed as a duplicate for this one.
If one wants to split string while keeping separators by regex without capturing group:
If one assumes that regex is wrapped up into capturing group:
Both ways also will remove empty groups which are useless and annoying in most of the cases.
install wrs «WITHOUT REMOVING SPLITOR» BY DOING
(developed by Rao Hamza)
result: [‘now ‘, ‘inbox “how to make ‘, ‘spam ad” invest in hard ‘, ’email marketing.’]
I had a similar issue trying to split a file path and struggled to find a simple answer. This worked for me and didn’t involve having to substitute delimiters back into the split text:
[‘folder1/’, ‘folder2/’, ‘folder3/’, ‘file1’]
I found this generator based approach more satisfying:
It avoids the need to figure out the correct regex, while in theory should be fairly cheap. It doesn’t create new string objects and, delegates most of the iteration work to the efficient find method.
. and in Python 3.8 it can be as short as:
May I just leave it here
Some of those answers posted before, will repeat delimiter, or have some other bugs which I faced in my case. You can use this function, instead:
Not the answer you’re looking for? Browse other questions tagged python regex or ask your own question.
Linked
Related
Hot Network Questions
Subscribe to RSS
To subscribe to this RSS feed, copy and paste this URL into your RSS reader.
By clicking “Accept all cookies”, you agree Stack Exchange can store cookies on your device and disclose information in accordance with our Cookie Policy.
Источники информации:
- http://stackoverflow.com/questions/234512/splitting-strings-in-python
- http://stackoverflow.com/questions/1838674/how-to-split-a-string-in-python
- http://stackoverflow.com/questions/4978787/how-do-i-split-a-string-into-a-list-of-characters
- http://stackoverflow.com/questions/2136556/in-python-how-do-i-split-a-string-and-keep-the-separators