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

0 votes

Hey guys, I was building a programme for my school computer exercise which involved me to replace the first and last word of a string. Now I've done it using my own indigenous ways but I'm rather interested to learn the most efficient way I could do it using Python

a = "this is the demo sentence."

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

b = "This is the demo 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. "

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

Aug 23, 2018 in Python by charlie_brown
• 7,780 points

edited Aug 23, 2018 by charlie_brown 1,302 views

1 answer to this question.

0 votes
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:,


 This is a demonstration Sentence. 
answered Aug 23, 2018 by aryya
• 7,440 points

Related Questions In Python

+1 vote
2 answers

How to print first character of each word in upper case of a string in Python

class Solution:     def firstAlphabet(self, s):             self.s=s              k=''              k=k+s[0]              for i in range(len(s)):                     if ...READ MORE

answered Oct 28, 2020 in Python by Anurag
0 votes
1 answer

How to capitalize the first word of string?

Refer to the below command: txt = "hello" x = ...READ MORE

answered Apr 4, 2019 in Python by Giri
+1 vote
1 answer
0 votes
2 answers
+1 vote
2 answers

how can i count the items in a list?

Syntax :            list. count(value) Code: colors = ['red', 'green', ...READ MORE

answered Jul 7, 2019 in Python by Neha
• 330 points

edited Jul 8, 2019 by Kalgi 2,472 views
0 votes
1 answer
+5 votes
6 answers

Lowercase in Python

You can simply the built-in function in ...READ MORE

answered Apr 11, 2018 in Python by hemant
• 5,810 points
0 votes
1 answer

Can someone explain the behaviour of increment and decrement operators in python

down voteaccepted ++ is not an operator. It is ...READ MORE

answered May 15, 2018 in Python by aryya
• 7,440 points
0 votes
1 answer

How to get the size of a string in Python?

If you are talking about the length ...READ MORE

answered Jun 4, 2018 in Python by aryya
• 7,440 points