Python Forum

Full Version: replace white space with a string, is this pythonic?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
i need to replace a run of white space characters by a string, which is usually a single character (but not always). for example: "foo \t bar" -> "foo_bar". is this a pythonic way to do that?
    replace_with = "_" # or this gets set some other way
    convert_this = "foo \t bar" # or this gets set some other way
    result = replace_with.join(convert_this.split())
or is there a better one like a not-known-to-me way to specify a run of white space in str.replace()?
basically yes
>>> s = 'foo \t bar'.split()
>>> s
['foo', 'bar']
>>> '_'.join(s)
'foo_bar'