Helpful Information
 
 
Category: Python Programming
split a string on odd characters

import string

def specialsplit(str, split):
str2list = string.split(str,split)
nlist=[]
for item in str2list:
if item == str2list[-1]:# skip last
nlist.append(item)
else:
nlist = nlist+[item,split]

return nlist


print specialsplit("peter@bengtsson","@")
# returns ['peter', '@', 'bengtsson']


-------------------

Is there a better way to do this? A Builtin or something perhaps.

toy around with the string.index() function. It errors when the value does not exist in the string (example: "hello".index("z")) so you'll need a try statement, but that should make it faster. Plus you wont need to "import string" (probably)

You can do it with list comprehension like this:


foo = 'peter@bengtsson'

bar = [[x, '@'] for x in foo.split('@')]
print(bar)

baz = [item for entry in bar for item in entry]
print(baz)

quux = baz[0 : -1]
print quux


Or if you're feeling like a perl programmer :D, you could try and cram it all into one statement:


foo = 'peter@bengtsson'
quux = [ item for entry in [[x, '@'] for x in foo.split('@')] for item in entry][0 : -1]
print(quux)

Crap, didn't realize the OP posted in 2001. I suck.

Crap, didn't realize the OP posted in 2001. I suck.

Never mind that :) I wonder why .partition() method won’t do?

foo = 'peter@bengtsson'
print(foo.partition('@'))
# prints ('peter', '@', 'bengtsson')
# ...and can be cast into a list with list()










privacy (GDPR)