What's the quickest/cleanest way to remove the first word of a string? I know I can use split
and then iterate on the array to get my string. But I'm pretty sure it's not the nicest way to do it.
Ps: I'm quite new to python and I don't know every trick.
Thanks in advance for your help.
To remove the first word from a string, call the indexOf() method to get the index of the first space in the string. Then use the substring() method to get a portion of the string, with the first word removed.
Method #1: Using split() Method This task can be performed using the split function which performs a split of words and separates the first word of string with the entire words.
Remove a Word from String using replace() print("Enter String: ", end="") text = input() print("Enter a Word to Delete: ", end="") word = input() wordlist = text. split() if word in wordlist: text = text.
I think the best way is to split, but limit it to only one split by providing maxsplit
parameter:
>>> s = 'word1 word2 word3' >>> s.split(' ', 1) ['word1', 'word2 word3'] >>> s.split(' ', 1)[1] 'word2 word3'
A naive solution would be:
text = "funny cheese shop" print text.partition(' ')[2] # cheese shop
However, that won't work in the following (admittedly contrived) example:
text = "Hi,nice people" print text.partition(' ')[2] # people
To handle this, you're going to need regular expressions:
import re print re.sub(r'^\W*\w+\W*', '', text)
More generally, it's impossible to answer a question involving "word" without knowing which natural language we're talking about. How many words is "J'ai"? How about "中华人民共和国"?
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With