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
  identify not white pixels in bmp flash77 17 2,269 Nov-10-2023, 09:21 PM
Last Post: flash77
  Need to replace a string with a file (HTML file) tester_V 1 699 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 1,147 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 1,545 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  Removing Space between variable and string in Python coder_sw99 6 6,123 Aug-23-2022, 01:15 PM
Last Post: louries
  Remove a space between a string and variable in print sie 5 1,706 Jul-27-2022, 02:36 PM
Last Post: deanhystad
  Find and Replace numbers in String giddyhead 2 1,197 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  Replace String in multiple text-files [SOLVED] AlphaInc 5 7,962 Aug-08-2021, 04:59 PM
Last Post: Axel_Erfurt
  Replace String with increasing numer [SOLVED] AlphaInc 13 4,919 Aug-07-2021, 08:16 AM
Last Post: perfringo
  How to replace on char with another in a string? korenron 3 2,293 Dec-03-2020, 07:37 AM
Last Post: korenron

Forum Jump:

User Panel Messages

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