2

Lets say I have a String: The Quick Brown Fox. I want to insert a character in place of the spaces. So that it becomes:

The-Quick-Brown-Fox

I could do that manually by iterating throughout the string checking for spaces. But I was wondering if there's a elegant way of doing that by using some python built-in functions?

xan
  • 4,640
  • 13
  • 50
  • 83

1 Answers1

7
>>> 'The Quick Brown Fox'.replace(' ', '-')
'The-Quick-Brown-Fox'

Maybe you want to replace any whitespace, in which case:

>>> '-'.join('The   Quick  \nBrown\t Fox'.split())
'The-Quick-Brown-Fox'

or using regex:

>>> import re
>>> re.sub(r'\s+', '-', 'The   Quick  \nBrown\t Fox')
'The-Quick-Brown-Fox'
jamylak
  • 128,818
  • 30
  • 231
  • 230