Python Forum
replace white space with a string, is this pythonic? - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: replace white space with a string, is this pythonic? (/thread-19221.html)



replace white space with a string, is this pythonic? - Skaperen - Jun-18-2019

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()?


RE: replace white space with a string, is this pythonic? - metulburr - Jun-18-2019

basically yes
>>> s = 'foo \t bar'.split()
>>> s
['foo', 'bar']
>>> '_'.join(s)
'foo_bar'