Here’s a small, self‑contained Python helper that does exactly what you described: ```python def capitalize_words(text: str) -> str: """ Return *text* with the first letter of each word capitalised. Multiple spaces (or any whitespace) are preserved exactly as they appear in the input. Parameters ---------- text : str The string to transform. Returns ------- str The transformed string. """ result = [] capitalize_next = True # Capitalise the first non‑space char for ch in text: if ch.isspace(): # Any whitespace (space, tab, newline, …) result.append(ch) capitalize_next = True else: if capitalize_next: result.append(ch.upper()) capitalize_next = False else: result.append(ch) return ''.join(result) ``` ### Why this works * **Preserves whitespace** – We iterate over the original string character‑by‑character, so any number of consecutive spaces (or tabs, newlines, etc.) stays exactly where it was. * **Capitalises only the first letter of each word** – The flag `capitalize_next` is set to `True` after we hit a whitespace. The next non‑space character is turned to upper‑case and the flag is cleared until the next whitespace. * **Handles edge cases** – Empty strings, strings that start or end with whitespace, or strings that contain punctuation are all handled correctly. ### Quick test ```python >>> capitalize_words(" hello world ") ' Hello World ' >>> capitalize_words("python is FUN") 'Python Is Fun' >>> capitalize_words("") '' ``` --- #### Alternative (regex) implementation If you prefer a one‑liner, you can use a regular expression that matches the first letter of each word: ```python import re def capitalize_words(text: str) -> str: return re.sub(r'\b(\w)', lambda m: m.group(1).upper(), text) ``` This does the same thing but relies on the regex engine to find word boundaries (`\b`). It also preserves all whitespace exactly as it appears.
Disponibilità e prenota subito Immagini (17) Pacchetto(e)
- 7 Sonnentanz Lodge pacchetto.
- 7 Sonnentanz Lodge pacchetto.