Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python: how to remove only first word from a string

Tags:

python-2.7

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

like image 587
Joe Dubey Avatar asked Dec 31 '12 06:12

Joe Dubey


People also ask

How do you remove the first word 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 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 I remove a specific word from a string in Python?

text = input('Enter a string: ') words = text. split() data = input('Enter a word to delete: ') status = False for word in words: if word == data: words. remove(word) status = True if status: text = ' '. join(words) print('String after deletion:',text) else: print('Word not present in string.

How do you extract the first part of a string in Python?

You can get the first character of a string by using the index 0. Where, string – Source string to extract the substring. [0] – To get the first character of the String.


3 Answers

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]
like image 86
Moshe Avatar answered Dec 03 '22 22:12

Moshe


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'
like image 40
RocketDonkey Avatar answered Dec 03 '22 20:12

RocketDonkey


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'
like image 42
Blender Avatar answered Dec 03 '22 20:12

Blender