以最python的方式替换字符串的第一个和最后一个单词

2024-09-28 19:10:30 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在寻找一种最具python风格的方法来替换字符串的第一个和最后一个单词(由于各种原因,以字母为基础进行替换是行不通的)。为了证明我在做什么,这里有一个例子。在

a = "this is the demonstration sentence."

我希望python函数的结果是:

^{pr2}$

最棘手的是,在字符串的前面或结尾可能有空格。我需要保存这些。在

我的意思是:

a = " this is a demonstration sentence. "

结果需要:

b = " This is a demonstration Sentence. "

他还想知道正则表达式是否比python的内置方法做得更好,反之亦然。在


Tags: the方法函数字符串证明is风格字母
3条回答

这对你有用吗:

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.'

下面是一个regex解决方案:

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. '

对不起,我只能这么做了。。。在

正则表达式分解:

^{2}$
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))

收益率

^{2}$

相关问题 更多 >