用最恐怖的方式替换第一个和最后一个字符串
发布时间:2020-12-30 09:24:25  所属栏目:Python  来源:互联网 
            导读:我正在寻找用于替换字符串的第一个和最后一个字的最 pythonic方式(在字母的基础上执行它不会因各种原因而起作用).为了演示我正在尝试做什么,这是一个例子. a = this is the demonstration sentence. 我希望我的python函数的结果是: b = This is the demonstr
                
                
                
            | 
                         我正在寻找用于替换字符串的第一个和最后一个字的最 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. (编辑:莱芜站长网) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!  | 
                  
