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?

4

1 回答 1

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

也许您想替换任何空格,在这种情况下:

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

或使用正则表达式:

>>> import re
>>> re.sub(r'\s+', '-', 'The   Quick  \nBrown\t Fox')
'The-Quick-Brown-Fox'
于 2013-05-22T10:39:49.270 回答