用两个不同的分隔符拆分字符串,将两个单词大写,只包含分隔符,然后再添加两个分隔符的最佳方法是什么?

Best way to split a string by two different delimiters, capitalize the two words encasing either delimiter only, and adding both delimiters back in?

我正在编写一个 Python 脚本,它应该能够用两个定界符拆分字符串:'_' 和 '.',将被定界符拆分的两个单词都大写(包含定界符),然后最后将分隔符放回原来的位置。

所以是这样的:this_is.an_Example string for.You

应该变成:This_Is.An_Example string For.You

现在我有这个:return '_'.join(x.capitalize() for x in re.split('_|\.', str)) + '\n' 这并不是我想要的。

有什么干净的方法可以做到这一点? 感谢您的帮助!

您可以使用

import re
s = "this_is.an_Example string for.You"
print(re.sub( r'(?<![^_.])[^\W_]+|[^\W_]+(?=[._])', lambda x: x.group().capitalize(), s))
# => This_Is.An_Example string For.You

参见Python demo and the regex demo

图案详情

  • (?<![^_.])[^\W_]+ - 1 个或多个数字或字母 ([^\W_]+) 紧接在 _. 或字符串开头
  • | - 或
  • [^\W_]+(?=[._]) - 1 个或多个数字或字母 ([^\W_]+) 紧跟 _、或 . 或字符串结尾。