Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove the first word in a Python string?

Tags:

python

string

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.

like image 342
Matthieu Riegler Avatar asked Oct 14 '12 14:10

Matthieu Riegler


People also ask

How do you remove the first word of a string?

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.

How do you remove the first 4 words of a string in Python?

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.

How do you remove a specific word from text in Python?

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.


2 Answers

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' 
like image 162
ovgolovin Avatar answered Sep 19 '22 09:09

ovgolovin


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 "中华人民共和国"?

like image 28
georg Avatar answered Sep 20 '22 09:09

georg