How to break a string in Python?

I read the documentation, but do not quite understand how to do this.

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 (if I can’t target first place in the sentence?).

So, for example, how would I split up: "Sico87 is an awful python developer" to "Sico87" and "is an awful Python developer" ?

Rows are retrieved from the database (if that matters).

+6
python string
source share
2 answers

Use partition(' ') , which always returns three elements in a tuple - the first bit before the delimiter, delimiter, and then the bit after. Slots in the tuple that are not applicable still exist, are simply set as empty lines.

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 similarly but returns a variable . It will return a tuple of one or two elements, the first element will be the first word before the separator, and the second will be the rest of the string (if any).

+14
source share

Use the split method for strings:

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

How it works:

  • Each row is an object. String objects have specific methods defined in them, for example split in this case. You call them with obj.<methodname>(<arguments>) .
  • The first argument to split is a character that separates the individual substrings. In this case, this is a space, ' ' .
  • The second argument is the number of times the split should be executed. In your case, this is 1 . Leaving this second argument, the split is applied as often as possible:

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

Of course, you can also store 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 note that this will cause a problem 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 
+19
source share

All Articles