Joe Dubey
Joe Dubey

Reputation: 131

Python: how to remove only first word from a string

The input string is given below:

line = "Cat Jumped the Bridge"

Output should be "Jumped the Bridge".

I tried

s2 = re.match('\W+.*', line).group()

But it returns

Traceback (most recent call last):
  File "regex.py", line 7, in <module>
    s2 = re.match('\W+.*', line).group()
AttributeError: 'NoneType' object has no attribute 'group'

So apparently the match failed.

Thanks for any suggestions. Joe

Upvotes: 13

Views: 27813

Answers (6)

Jonathan Griffin
Jonathan Griffin

Reputation: 11

def delete_first_word(p):
    letter = 0
    for e in p:
        if e[0] == " ":
            return line[letter + 1:]
        else:
            letter = letter + 1
line = "Cat Jumped the Bridge"
print delete_first_word(line)

Upvotes: 0

Moshe
Moshe

Reputation: 9899

Python's split has an optional second parameter called maxsplit, to specify the largest amount of splits:

line = "Cat Jumped the Bridge"
s2 = line.split(' ', 1)[1]

To quote the docs for str.split:

Return a list of the words in the string, using sep as the delimiter string. If maxsplit is given, at most maxsplit splits are done

So to explain this code: str.split(' ', 1) creates a list with two elements: the first element being the first word (until it reaches a space), and the second being the rest of the string. To only extract the rest of the string, we use [1] to indicate the second element.

Note: If you are concerned about having multiple spaces, use None as the first parameter for str.split, as follows:

line = "Cat Jumped the Bridge"
s2 = line.split(None, 1)[1]

Upvotes: 20

user3818650
user3818650

Reputation: 571

Or.........

words = ["Cat", "Cool", "Foo", "Mate"]
sentence = "Cat Jumped the Bridge"

for word in words:
    if word in sentence:
        sentence = sentence.replace(word, "", 1)
        break

Otherwise....

sentence = "Cat Jumped the Bridge"

sentence = sentence.split(" ")
sentence.pop(0)
sentence = " ".join(sentence)

Upvotes: 1

Sufian Latif
Sufian Latif

Reputation: 13356

Can be simpler:

line = "Cat Jumped the Bridge"
s2 = " ".join(line.split()[1:])

Using regex:

line = "Cat Jumped the Bridge"
s2 = re.sub('^\S+\s+', '', line)

Upvotes: 3

Blender
Blender

Reputation: 298412

You can also use .partition():

>>> line = "Cat Jumped the Bridge"
>>> word, space, rest = line.partition(' ')
>>> word
'Cat'
>>> space
' '
>>> rest
'Jumped the Bridge'

To fix what you have now, add a capturing group and use \w instead of \W (they're opposites):

>>> re.match(r'(\w+)', line).group()
'Cat'

Upvotes: 5

RocketDonkey
RocketDonkey

Reputation: 37269

If you aren't tied to regular expression, you could do something like this:

In [1]: line = "Cat Jumped the Bridge"

In [2]: s2 = ' '.join(line.split()[1:])

In [3]: s2
Out[3]: 'Jumped the Bridge'

line.split() takes the string and splits it on whitespace, returning a list that contains each word as an items:

In [4]: line.split()
Out[4]: ['Cat', 'Jumped', 'the', 'Bridge']

From that list, we take the second element (skipping the first word) and everything after it by using [1:]:

In [5]: line.split()[1:]
Out[5]: ['Jumped', 'the', 'Bridge']

And then last piece is joining it all together using join, where here we use the space character to 'join' all of the strings in our list back into a single string:

In [6]: ' '.join(line.split()[1:])
Out[6]: 'Jumped the Bridge'

Upvotes: 5

Related Questions