我正在寻找用于替换字符串的第一个和最后一个字的最
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.