LearnFrenzy
Sign in Take a free test

Regular Expressions · Predict the Output · Question 7

Collapsing whitespace with sub() Answer, explanation & discussion

  • Output
  • Easy
  • 0 comments
  • Answer explained
  • Moderated community
Question 7 Back to Exercise

What is the output of the following Python program?

main.py
import re
print(repr(re.sub(r"\s+", " ", "  a   b \t c ")), re.sub(r"a", "X", "banana", count=2))
  • A 'a b c' bXnXnX
  • B ' a b c ' bXnXna Correct
  • C ' a b c ' bXnXnX
  • D 'a b c' bXnXna
Correct Answer: Option B

Each run of whitespace (including the ones at the ends) becomes one space. count=2 replaces only the first two matches.

Discussion & Comments 0

Share your method, a shortcut, or ask about a step you didn't follow.

No comments yet. Be the first to share your solution!

Post your comment

Comments appear after a quick review by our team.

Search LearnFrenzy

Esc

Quick links