加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

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

发布时间:2020-12-16 23:22:18 所属栏目:Python 来源:网络整理
导读:我正在寻找用于替换字符串的第一个和最后一个字的最 pythonic方式(在字母的基础上执行它不会因各种原因而起作用).为了演示我正在尝试做什么,这是一个例子. a = "this is the demonstration sentence." 我希望我的python函数的结果是: b = "This is the demo
我正在寻找用于替换字符串的第一个和最后一个字的最 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.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读