views:

155

answers:

2

Hello,

I looking to split a string up with 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 the string(unless I can target the first space in the sentence?)

So for example how would I split "Sico87 is an awful python developer" into "Sico87" and "is an awful Python developer"

It if changes anything the strings are being pulled from a database.

Thanks

+6  A: 

Use partition(' ') which always returns three items in the tuple - the first bit up until the separator, the separator, and then the bits after. Slots in the tuple that have are not applicable are still there, just set to be empty strings.

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).

Will
Wrong usage of the `maxsplit` argument
abyx
thx abyx, saw and fixed it while you were adding your comment :)
Will
I don't know if I'd say split with maxsplit is trickier, it just makes tuple unpacking not work. I'm in strong agreement with using partition + tuple unpacking for cases like this, though; it's concise and consistent.
Jeffrey Harris
+15  A: 

Use the split method on strings:

>>> "Sico87 is an awful python developer".split(' ', 1)
['Sico87', 'is an awful python developer']

How it works:

  1. Every string is an object. String objects have certain methods defined on them, such as split in this case. You call them using obj.<methodname>(<arguments>).
  2. The first argument to split is the character that separates the individual substrings. In this case that is a space, ' '.
  3. The second argument is the number of times the split should be performed. In your case that is 1. Leaving out this second argument applies the split as often as possible:

    >>> "Sico87 is an awful python developer".split(' ')
    ['Sico87', 'is', 'an', 'awful', 'python', 'developer']
    

Of course you can also store the substrings in separate variables instead of a list:

>>> a, b = "Sico87 is an awful python developer".split(' ', 1)
>>> a
'Sico87'
>>> b
'is an awful python developer'

But do note that this will cause trouble if certain inputs do not contain spaces:

>>> a, b = "string_without_spaces".split(' ', 1)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: need more than 1 value to unpack
Stephan202