How to remove space before comma in Python?

Member

by sabryna , in category: Python , 2 years ago

How to remove space before comma in Python?

Facebook Twitter LinkedIn Telegram Whatsapp

2 answers

by filomena_oreilly , 2 years ago

@sabryna The algorithm is to replace all " ," to a simple comma. Here is code as example how to remove a space before comma in Python:


1
2
3
str = 'test , string , as , example'
# Output: test, string, as, example
print(str.replace(" ,", ","))


Member

by tina , a year ago

@sabryna 

There are multiple ways to remove space before a comma in Python. Here are a few methods:

  1. Using replace() method:


The replace() method replaces all occurrences of a specified substring with another substring. We can use it to replace space before a comma with an empty string.

1
2
3
string = "hello , world"
string = string.replace(" ,", ",")
print(string)  # Output: "hello, world"


  1. Using regex:


Python's re module provides regular expression operations. We can use regex to match space before a comma and replace it with an empty string.

1
2
3
4
5
import re

string = "hello , world"
string = re.sub("s+,", ",", string)
print(string)  # Output: "hello, world"


  1. Using split() and join() methods:


We can split the string using comma as the separator, strip the spaces from each part of the string, and then join them using a comma as the separator again.

1
2
3
4
string = "hello , world"
parts = [part.strip() for part in string.split(",")]
string = ",".join(parts)
print(string)  # Output: "hello, world"