Python Forum
replace white space with a string, is this pythonic?
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
replace white space with a string, is this pythonic?
#1
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()?
Tradition is peer pressure from dead people

What do you call someone who speaks three languages? Trilingual. Two languages? Bilingual. One language? American.
Reply
#2
basically yes
>>> s = 'foo \t bar'.split()
>>> s
['foo', 'bar']
>>> '_'.join(s)
'foo_bar'
Recommended Tutorials:
Reply


Possibly Related Threads…
Thread Author Replies Views Last Post
  White Screen Issue with Toolbar After Python Installation evelynfreya 2 995 Nov-25-2024, 06:26 PM
Last Post: deanhystad
Question [SOLVED] How to replace characters in a string? Winfried 2 978 Sep-04-2024, 01:41 PM
Last Post: Winfried
  identify not white pixels in bmp flash77 17 7,472 Nov-10-2023, 09:21 PM
Last Post: flash77
  Pythonic from a C++ perspective PyDan 2 1,379 Sep-18-2023, 11:39 AM
Last Post: PyDan
  Need to replace a string with a file (HTML file) tester_V 1 1,869 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 2,356 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 2,744 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  Removing Space between variable and string in Python coder_sw99 6 10,539 Aug-23-2022, 01:15 PM
Last Post: louries
  Remove a space between a string and variable in print sie 5 2,848 Jul-27-2022, 02:36 PM
Last Post: deanhystad
  Find and Replace numbers in String giddyhead 2 2,920 Jul-17-2022, 06:22 PM
Last Post: giddyhead

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020