This question already has answers here:
Closed 11 years ago.
Possible Duplicate:
Python split string on regex
How do I split some text using Python's re module into two parts: the text before a special word cut and the rest of the text following it.
You can do it with re:
>>> import re
>>> re.split('cut', s, 1) # Split only once.
But in this case you can just use str.split:
>>> s.split('cut', 1) # Split only once.
Check this, might help you
>>> re.compile('[0-9]+').split("hel2l3o")
['hel', 'l', 'o']
>>>
>>> re.compile('cut').split("hellocutworldcutpython")
['hello', 'world', 'python']
split about first cut
>>> l=re.compile('cut').split("hellocutworldcutpython")
>>> print l[0], string.join([l[i] for i in range(1, len(l))], "")
hello worldpython
Related
This question already has answers here:
Split Strings into words with multiple word boundary delimiters
(31 answers)
Closed 8 years ago.
I found some answers online, but I have no experience with regular expressions, which I believe is what is needed here.
I have a string that needs to be split by either a ';' or ', '
That is, it has to be either a semicolon or a comma followed by a space. Individual commas without trailing spaces should be left untouched
Example string:
"b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3], mesitylene [000108-67-8]; polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]"
should be split into a list containing the following:
('b-staged divinylsiloxane-bis-benzocyclobutene [124221-30-3]' , 'mesitylene [000108-67-8]', 'polymerized 1,2-dihydro-2,2,4- trimethyl quinoline [026780-96-1]')
Luckily, Python has this built-in :)
import re
re.split('; |, ', string_to_split)
Update:Following your comment:
>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']
Do a str.replace('; ', ', ') and then a str.split(', ')
Here's a safe way for any iterable of delimiters, using regular expressions:
>>> import re
>>> delimiters = "a", "...", "(c)"
>>> example = "stackoverflow (c) is awesome... isn't it?"
>>> regex_pattern = '|'.join(map(re.escape, delimiters))
>>> regex_pattern
'a|\\.\\.\\.|\\(c\\)'
>>> re.split(regex_pattern, example)
['st', 'ckoverflow ', ' is ', 'wesome', " isn't it?"]
re.escape allows to build the pattern automatically and have the delimiters escaped nicely.
Here's this solution as a function for your copy-pasting pleasure:
def split(delimiters, string, maxsplit=0):
import re
regex_pattern = '|'.join(map(re.escape, delimiters))
return re.split(regex_pattern, string, maxsplit)
If you're going to split often using the same delimiters, compile your regular expression beforehand like described and use RegexObject.split.
If you'd like to leave the original delimiters in the string, you can change the regex to use a lookbehind assertion instead:
>>> import re
>>> delimiters = "a", "...", "(c)"
>>> example = "stackoverflow (c) is awesome... isn't it?"
>>> regex_pattern = '|'.join('(?<={})'.format(re.escape(delim)) for delim in delimiters)
>>> regex_pattern
'(?<=a)|(?<=\\.\\.\\.)|(?<=\\(c\\))'
>>> re.split(regex_pattern, example)
['sta', 'ckoverflow (c)', ' is a', 'wesome...', " isn't it?"]
(replace ?<= with ?= to attach the delimiters to the righthand side, instead of left)
In response to Jonathan's answer above, this only seems to work for certain delimiters. For example:
>>> a='Beautiful, is; better*than\nugly'
>>> import re
>>> re.split('; |, |\*|\n',a)
['Beautiful', 'is', 'better', 'than', 'ugly']
>>> b='1999-05-03 10:37:00'
>>> re.split('- :', b)
['1999-05-03 10:37:00']
By putting the delimiters in square brackets it seems to work more effectively.
>>> re.split('[- :]', b)
['1999', '05', '03', '10', '37', '00']
This is how the regex look like:
import re
# "semicolon or (a comma followed by a space)"
pattern = re.compile(r";|, ")
# "(semicolon or a comma) followed by a space"
pattern = re.compile(r"[;,] ")
print pattern.split(text)
This question already has answers here:
How to extract the substring between two markers?
(22 answers)
Closed 4 years ago.
I have a string - Python :
string = "/foo13546897/bar/Atlantis-GPS-coordinates/bar457822368/foo/"
Expected output is :
"Atlantis-GPS-coordinates"
I know that the expected output is ALWAYS surrounded by "/bar/" on the left and "/" on the right :
"/bar/Atlantis-GPS-coordinates/"
Proposed solution would look like :
a = string.find("/bar/")
b = string.find("/",a+5)
output=string[a+5,b]
This works, but I don't like it.
Does someone know a beautiful function or tip ?
You can use split:
>>> string.split("/bar/")[1].split("/")[0]
'Atlantis-GPS-coordinates'
Some efficiency from adding a max split of 1 I suppose:
>>> string.split("/bar/", 1)[1].split("/", 1)[0]
'Atlantis-GPS-coordinates'
Or use partition:
>>> string.partition("/bar/")[2].partition("/")[0]
'Atlantis-GPS-coordinates'
Or a regex:
>>> re.search(r'/bar/([^/]+)', string).group(1)
'Atlantis-GPS-coordinates'
Depends on what speaks to you and your data.
What you haven't isn't all that bad. I'd write it as:
start = string.find('/bar/') + 5
end = string.find('/', start)
output = string[start:end]
as long as you know that /bar/WHAT-YOU-WANT/ is always going to be present. Otherwise, I would reach for the regular expression knife:
>>> import re
>>> PATTERN = re.compile('^.*/bar/([^/]*)/.*$')
>>> s = '/foo13546897/bar/Atlantis-GPS-coordinates/bar457822368/foo/'
>>> match = PATTERN.match(s)
>>> match.group(1)
'Atlantis-GPS-coordinates'
import re
pattern = '(?<=/bar/).+?/'
string = "/foo13546897/bar/Atlantis-GPS-coordinates/bar457822368/foo/"
result = re.search(pattern, string)
print string[result.start():result.end() - 1]
# "Atlantis-GPS-coordinates"
That is a Python 2.x example. What it does first is:
1. (?<=/bar/) means only process the following regex if this precedes it (so that /bar/ must be before it)
2. '.+?/' means any amount of characters up until the next '/' char
Hope that helps some.
If you need to do this kind of search a bunch it is better to 'compile' this search for performance, but if you only need to do it once don't bother.
Using re (slower than other solutions):
>>> import re
>>> string = "/foo13546897/bar/Atlantis-GPS-coordinates/bar457822368/foo/"
>>> re.search(r'(?<=/bar/)[^/]+(?=/)', string).group()
'Atlantis-GPS-coordinates'
This question already has answers here:
How do I split a multi-line string into multiple lines?
(6 answers)
Closed 8 years ago.
Example:
string = """i like to program
i need attention
12345 67890
abcdefghijkl mnopqrstuvwxyz"""
string = function(string)
print(string)
["i like to program" ,"i need attention", "12345 67890", "abcdefghijkl mnopqrstuvwxyz"]
Note, i know about the split() function, i just want to know if there is any function that splits only lines and not spaces.
As #iCodez suggests, it's best to use str.splitlines.
While, on first sight, this may seem the same as doing split('\n'), they have different behaviours.
\n on python represents a line-break, independently from the platform where you run it. However, this representation is platform-dependent. On windows, \n is two characters, CR and LF (ASCII decimal codes 13 and 10), while on any modern unix (including OS X), it's the single character LF.
print, for example, works correctly even if you have a string with line endings that don't match your platform:
>>> print "a\x0ab\x0d\x0ac"
a
b
c
However, explicitly splitting on "\n", will yield platform-dependent behaviour:
>>> "a\x0ab\x0d\x0ac".split("\n")
['a', 'b\r', 'c']
For this reason, it's best to use splitlines:
>>> "a\x0ab\x0d\x0ac".splitlines()
['a', 'b', 'c']
string.split('\n') will suffice. Or explicitly string.splitlines.
You can use str.splitlines:
>>> string = """i like to program
... i need attention
... 12345 67890
... abcdefghijkl mnopqrstuvwxyz"""
>>> string.splitlines()
['i like to program', 'i need attention', '12345 67890', 'abcdefghijkl mnopqrstuvwxyz']
>>>
This question already has answers here:
How to convert string to Title Case in Python?
(10 answers)
Closed 9 years ago.
I'm having trouble trying to create a function that can do this job. The objective is to convert strings like
one to One
hello_world to HelloWorld
foo_bar_baz to FooBarBaz
I know that the proper way to do this is using re.sub, but I'm having trouble creating the right regular expressions to do the job.
You can try something like this:
>>> s = 'one'
>>> filter(str.isalnum, s.title())
'One'
>>>
>>> s = 'hello_world'
>>> filter(str.isalnum, s.title())
'HelloWorld'
>>>
>>> s = 'foo_bar_baz'
>>> filter(str.isalnum, s.title())
'FooBarBaz'
Relevant documentation:
str.title()
str.isalnum()
filter()
Found solution:
def uppercase(name):
return ''.join(x for x in name.title() if not x.isspace()).replace('_', '')
new_str="##2##*##1"
new_str1="##3##*##5##7"
How to split the above string in python
for val in new_str.split("##*"):
logging.debug("=======")
logging.debug(val[2:]) // will give
for st in val.split("##*"):
//how to get the values after ## in new_str and new_str1
I don't understand the question.
Are you trying to split a string by a delimiter? Then use split:
>>> a = "##2##*##1"
>>> b = "##3##*##5##7"
>>>
>>> a.split("##*")
['##2', '##1']
>>> b.split("##*")
['##3', '##5##7']
Are you trying to strip extraneous characters from a string? Then use strip:
>>> c = b.split("##*")[1]
>>> c
'##5##7'
>>> c.strip("#")
'5##7'
Are you trying to remove all the hashes (#) from a string? Then use replace:
>>> c.replace("#","")
'57'
Are you trying to find all the characters after "##"? Then use rsplit with its optional argument to split only once:
>>> a.rsplit("##",1)
['##2##*', '1']