user3898160
user3898160

Reputation: 539

Remove last word enclosed in backtick from string

I have the following string:

Input:
! Abc `xyzpqr` `abcd xyz` `test abc`
! Abc `xyzpqr` `abcd 123` `testabc`

I wish to remove the last word enclosed in the quotes.

Desired output:
! Abc `xyzpqr` `abcd xyz`
! Abc `xyzpqr` `abcd 123`

Using rsplit() I'm not getting correct output:

>>> text = "! Abc `xyzpqr` `abcd xyz` `test abc`"       
>>> text.rsplit(' ', 1)[0]
Output:
"! Abc `xyzpqr` `abcd xyz` `test"

How to get the desired output?

Upvotes: 0

Views: 412

Answers (1)

Andrej Kesely
Andrej Kesely

Reputation: 195543

You can use shlex module:

import shlex

s = "! Abc 'xyzpqr' 'abcd xyz' 'test abc'"

print( shlex.join(shlex.split(s)[:-1]) )

Prints:

'!' Abc xyzpqr 'abcd xyz'

If you don't want to ! quoted:

s = shlex.split(s)
print( s[0] + ' ' + shlex.join(s[1:-1]) )

Prints:

! Abc xyzpqr 'abcd xyz'

EDIT:

import shlex

s = '''! Abc `xyzpqr` `abcd xyz` `test abc`
! Abc `xyzpqr` `abcd 123` `testabc`'''

for line in s.splitlines():
    line = line.split(maxsplit = 3)
    line[-1] = shlex.join(shlex.split(line[-1].replace('`', '"'))[:-1])
    print(' '.join(line).replace("'", '`'))

Prints:

! Abc `xyzpqr` `abcd xyz`
! Abc `xyzpqr` `abcd 123`

Upvotes: 1

Related Questions