David Taglioni
David Taglioni

Reputation:

Need some help with python string / slicing operations

This is a very newbie question and i will probably get downvoted for it, but i quite honestly couldn't find the answer after at least an hour googling. I learned how to slice strings based on "exact locations" where you have to know exactly where the word ends. But i did not find any article that explained how do it on "non static" strings that could change.

Also i do not want to use string.split() in this case as its a little overkill for what i need.

I basically have a string like this:

myString = "!save python Python is a high-level object oriented language created by Guido van Rossum."
# the format is !save [singleword] [definition]

i need to "slice" this string but i cant figure out a proper way to do it.

i need to save a to variable the title (python in this case) and the definition of this string. Somethig like:

title = myString[1]
definition = myString[everything after string[1]

I'm not exactly sure how to do this when you have a dynamic string where you dont know where each word ends.

I would greatly appreciate some pointers on what functions/methods should i read on to archieve this. Thank you in advance.

Upvotes: 2

Views: 698

Answers (3)

John Machin
John Machin

Reputation: 82924

The selected answer (after PEP8ing):

verb, title, definition = my_string.split(' ', 2)

splits on a single space. It's likely a better choice to split on runs of whitespace, just in case there are tabs or multiple spaces on either side of the title:

verb, title, definition = my_string.split(None, 2)

Also consider normalising the whitespace in the definition:

definition = ' '.join(definition.split())

Upvotes: 1

Jesse Vogt
Jesse Vogt

Reputation: 16499

If you have spaces between your command, title, and definition you could:

wordList = myString.split()
cmd = wordList[0] # !save
title = wordList[1] # python
definition = ' '.join(wordList[2:])  # Python is a high-level object oriented language created by Guido van Rossum.

If you really would rather not use split you could use regular expressions:

import re
m = re.match('(/S+)/s*(/S+)/s*(.*)')
cmd = m.group(1)
title = m.group(2)
definition = m.group(3)

Upvotes: 2

Joe Holloway
Joe Holloway

Reputation: 28948

Why is split overkill?

verb, title, definition = myString.split (' ', 2)

Upvotes: 12

Related Questions