您的位置 首页 Python

用最恐怖的方式替换第一个和最后一个字符串

我正在寻找用于替换字符串的第一个和最后一个字的最
pythonic方式(在字母的基础上执行它不会因各种原因而起作用).为了演示我正在尝试做什么,这是一个例子.

a = "this is the demonstration sentence."

我希望我的python函数的结果是:

b = "This is the demonstration Sentence."

其中棘手的部分是字符串的前端或末端可能有空格.我需要保留这些.

这就是我的意思:

a = " this is a demonstration sentence. "

结果需要是:

b = " This is a demonstration Sentence. "

也会对正则表达式是否比python的内置方法更好地完成这项工作的意见感兴趣,反之亦然.

解决方法

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))

产量

This is a demonstration Sentence.

关于作者: dawei

【声明】:金华站长网内容转载自互联网,其相关言论仅代表作者个人观点绝非权威,不代表本站立场。如您发现内容存在版权问题,请提交相关链接至邮箱:bqsm@foxmail.com,我们将及时予以处理。

热门文章