Skip to content Skip to sidebar Skip to footer

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 (a

Solution 1:

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).

Solution 2:

Try: import re

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

Prints cool

Solution 3:

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

Solution 4:

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:

importstring

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'

Solution 5:

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.

Post a Comment for "Pythonically Remove The First X Words Of A String"