Python Forum
How to remove whitespace from a string when .replace and .strip do not work
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
How to remove whitespace from a string when .replace and .strip do not work
#2
try this
Remove ALL spaces in a string, even between words:

import re
sentence = re.sub(r"\s+", "", sentence, flags=re.UNICODE)
Remove spaces in the BEGINNING of a string:

import re
sentence = re.sub(r"^\s+", "", sentence, flags=re.UNICODE)
Remove spaces in the END of a string:

import re
sentence = re.sub(r"\s+$", "", sentence, flags=re.UNICODE)
Remove spaces both in the BEGINNING and in the END of a string:

import re
sentence = re.sub("^\s+|\s+$", "", sentence, flags=re.UNICODE)
Remove ONLY DUPLICATE spaces:

import re
sentence = " ".join(re.split("\s+", sentence, flags=re.UNICODE))
Reply


Messages In This Thread
RE: How to remove whitespace from a string when .replace and .strip do not work - by bvdinesh - Jan-04-2019, 10:05 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  remove gilberishs from a "string" kucingkembar 2 303 Mar-15-2024, 08:51 AM
Last Post: kucingkembar
  Need to replace a string with a file (HTML file) tester_V 1 800 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  Replace string in a nested Dictianory. SpongeB0B 2 1,254 Mar-24-2023, 05:09 PM
Last Post: SpongeB0B
  Replace with upper(string) WJSwan 7 1,636 Feb-10-2023, 10:28 AM
Last Post: WJSwan
  extract only text strip byte array Pir8Radio 7 3,061 Nov-29-2022, 10:24 PM
Last Post: Pir8Radio
Smile please help me remove error for string.strip() jamie_01 3 1,260 Oct-14-2022, 07:48 AM
Last Post: Pedroski55
  Remove a space between a string and variable in print sie 5 1,851 Jul-27-2022, 02:36 PM
Last Post: deanhystad
  Find and Replace numbers in String giddyhead 2 1,282 Jul-17-2022, 06:22 PM
Last Post: giddyhead
  How do I remove spurious "." from a string? Zuhan 7 2,128 Apr-12-2022, 02:06 PM
Last Post: Pedroski55
  Can't strip extra characters from Data Canflyguy 7 1,912 Jan-10-2022, 02:16 PM
Last Post: Canflyguy

Forum Jump:

User Panel Messages

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