Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace First and Last Word of String in the Most Pythonic Way

I am looking for the most pythonic way to replace the first and last word of a string (doing it on a letter basis won't work for various reasons). To demonstrate what I'm trying to do, here is an example.

a = "this is the demonstration sentence."

I'd like the result of my python function to be:

b = "This is the demonstration Sentence."

The tricky part of it is that there might be spaces on the front or the end of the string. I need those to be preserved.

Here's what I mean:

a = " this is a demonstration sentence. "

The result would need to be:

b = " This is a demonstration Sentence. "

Would also be interested in opinions on whether a regex would do this job better than python's inbuilt methods, or vice versa.

like image 673
Pat Avatar asked Nov 29 '12 01:11

Pat


People also ask

How do you replace multiple words in a string in Python?

Use the translate() method to replace multiple different characters. You can create the translation table specified in translate() by the str. maketrans() . Specify a dictionary whose key is the old character and whose value is the new string in the str.

How do you remove first and last words from a sentence in Python?

To remove the first and last words from a string: Use the index() and rindex() methods to get the indexes of the first and last spaces. Use string slicing to get a slice after the first space up to the last space. The new string won't contain the first and last words of the original string.

How do you split the last word in a sentence in Python?

You can split your text by last space symbol into two parts using rsplit. rsplit is a shorthand for "reverse split", and unlike regular split works from the end of a string.

What does replace () do in Python?

Python String replace() Method The replace() method replaces a specified phrase with another specified phrase. Note: All occurrences of the specified phrase will be replaced, if nothing else is specified.


3 Answers

import re
a = " this is a demonstration sentence. "
print(re.sub(r'''(?x)      # VERBOSE mode
             (             # 
              ^            # start of string
              \s*          # zero-or-more whitespaces 
              \w           # followed by an alphanumeric character
              )        
             |             # OR
             (
             \w            # an alphanumeric character
             \S*           # zero-or-more non-space characters
             \s*           # zero-or-more whitespaces
             $             # end of string
             )
             ''',
             lambda m: m.group().title(),
             a))

yields

 This is a demonstration Sentence. 
like image 64
unutbu Avatar answered Oct 21 '22 23:10

unutbu


Does this work for you:

In [9]: a = "this is the demonstration sentence."

In [10]: left, _, right = a.strip().partition(' ')

In [11]: mid, _, right = right.rpartition(' ')

In [12]: Left = left.title()

In [13]: Right = right.title()

In [14]: a = a.replace(left, Left, 1).replace(right, Right, 1)

In [15]: a
Out[15]: 'This is the demonstration Sentence.'
like image 34
inspectorG4dget Avatar answered Oct 22 '22 00:10

inspectorG4dget


Here's a regex solution:

def cap(m):
    return m.group(0).title()

re.sub(r'(?:^\s*\w+)|(?:[^\s]+\s*$)',cap," this is a demonstration sentence. ")
' This is a demonstration Sentence. '

Sorry, that's the best I can do ...

Regex breakdown:

(?:^\s*\w+)    #match (optional) whitespace and then 1 word at the beginning of the string
|              #regex "or"
(?:[^\s]+\s*$) #match a string of non-whitespace characters followed by (optional) whitespace and the end of the line.
like image 45
mgilson Avatar answered Oct 21 '22 23:10

mgilson