2

I need to change a sentence to have alternating capitalizations! Having trouble making it ignore the spacebar inputs...

input: the quick brown fox jumps over the lazy dog
output: tHe QuIcK bRoWn FoX jUmPs OvEr ThE lAzY dOg

I tried the following:

input: ([\w\s])([\w\s]?)
output: upper(\1)\2

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563
Baldur
  • 21
  • 1

1 Answers1

0

You can use

import re
text = "the quick brown fox jumps over the lazy dog"
print( re.sub(r"(\S)(\s*)(\S)", lambda x: f'{x.group(1).lower()}{x.group(2)}{x.group(3).upper()}', text) )
# tHe QuIcK bRoWn FoX jUmPs OvEr ThE lAzY dOg

See the Python demo.

The (\S)(\s*)(\S) regex matches and captures a non-whitespace char into Group 1, then captures zero or more whitespaces into Group 2 and then captures any whitespace into Group 3. The f'{x.group(1).lower()}{x.group(2)}{x.group(3).upper()}' replacement concatenates a lowercase Group 1 value, the whitespaces in Group 2 and an uppercased value in Group 3.

Wiktor Stribiżew
  • 607,720
  • 39
  • 448
  • 563