w3resource

Python: Insert spaces between words starting with capital letters


51. Insert Spaces Before Capitals

Write a Python program to insert spaces between words starting with capital letters.

Sample Solution:

Python Code:

import re
def capital_words_spaces(str1):
  return re.sub(r"(\w)([A-Z])", r"\1 \2", str1)

print(capital_words_spaces("Python"))
print(capital_words_spaces("PythonExercises"))
print(capital_words_spaces("PythonExercisesPracticeSolution"))

Sample Output:

Python
Python Exercises
Python Exercises Practice Solution 

Pictorial Presentation:

Python: Insert spaces between words starting with capital letters.
Python: Insert spaces between words starting with capital letters.

Flowchart:

Flowchart: Regular Expression - Insert spaces between words starting with capital letters.

For more Practice: Solve these Related Problems:

  • Write a Python program to insert a space before each uppercase letter in a camelCase string.
  • Write a Python script to modify a concatenated string of capitalized words by adding spaces between them.
  • Write a Python program to convert a string like "HelloWorldPython" to "Hello World Python" using regex.
  • Write a Python function to split a PascalCase string into separate words by inserting spaces before each capital letter.

Go to:


Previous: Write a Python program to remove the parenthesis area in a string.
Next: Write a Python program that reads a given expression and evaluates it.

Python Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.