Mawg
Mawg

Reputation: 40140

Pythonically remove the first X words of a string

How do I do it Pythonically?

I know how to delete the first word, but now I need to remove three.

Note that words can be delimited by amount of whitecap, not just a single space (although I could enforce a single white space if it must be so).


[Update] I mean any X words; I don't know hat they are.

I am considering looping and repeatedly removing the first word, joining together again, rinsing and repeating.

Upvotes: 0

Views: 3085

Answers (5)

Idos
Idos

Reputation: 15310

You can use split:

>>> x = 3 # number of words to remove from beginning
>>> s = 'word1 word2 word3 word4'
>>> s = " ".join(s.split()) # remove multiple spacing
>>> s = s.split(" ", x)[x] # split and keep elements after index x
>>> s
'word4'

This will handle multiple spaces as well.

Upvotes: 1

TheBoro
TheBoro

Reputation: 223

You can use the split function to do this. Essentially, it splits the string up into individual (space separated, by default) words. These words are stored in a list and then from that list, you can access the words you want, just like you would with a normal list of other data types. Using the desired words you can then join the list to form a string.

for example:

import string

str='This is    a bunch of words'

string_list=string.split(
#The string is now stored in a list that looks like: 
      #['this', 'is', 'a', 'bunch', 'of', 'words']

new_string_list=string_list[3:]
#the list is now: ['bunch', 'of', 'words']

new_string=string.join(new_string_list)
#you now have the string 'bunch of words'

You can also do this in fewer lines, if desired (not sure if this is pythonic though)

import string as st
str='this is a bunch     of words'
new_string=st.join(st.split(str[3:])
print new_string

#output would be 'bunch of words'

Upvotes: 1

minghan
minghan

Reputation: 1103

Try: import re

print re.sub("(\w+)", "", "a sentence is cool", 3)

Prints cool

Upvotes: 2

DevShark
DevShark

Reputation: 9112

s = "this    is my long     sentence"
print ' '.join(s.split(' ')[3:])

This will print

"long sentence"

Which I think is what you need (it will handle the white spaces the way you wanted).

Upvotes: 4

ajay_t
ajay_t

Reputation: 2385

This can be done by simple way as:

In [7]: str = 'Hello, this is long string'
In [8]: str = str[3:]
In [9]: str
Out[9]: 'lo, this is long string'
In [10]:

Now you can update 3 on line In[8] with your X

Upvotes: 1

Related Questions