How do you replace a character in a string with spaces in python?

I have a CSV file, where each comma delimited field is enclosed in " - eg. "fred", "bert", "blah". I am trying to use the replace function but can't seem to have it recognize the " character. example, if the record is in a string called buffer:

buffer.replace['\"','']

Maroun

92.2k30 gold badges187 silver badges236 bronze badges

asked Mar 31, 2015 at 9:17

4

Add space between double quotes

p = '"fred", "bert", "blah"'

p.replace['\"'," "]

' fred , bert , blah '

answered Mar 31, 2015 at 11:54

fahadfahad

2,7993 gold badges16 silver badges20 bronze badges

2

Why do you escape the double quotes if it's inside single quotes ?

Try the following :

a = '"my string"'
a = a.replace['"',' ']
print[a]
#=> ' my string '

answered Apr 1, 2015 at 8:51

You are not replacing it with space firstly, but with empty string

Try using buffer.strip["\""]

answered Mar 31, 2015 at 9:25

hyadeshyades

2,9501 gold badge15 silver badges34 bronze badges

1

To remove spaces from a string in Python, use the str.replace[] method.

This method takes two arguments:

  • The first argument is the string to be replaced.
  • The second argument is the string that replaces the string.

For example:

string = "This is a test"
nospaces = string.replace[" ", ""]

print[nospaces]

Output:

Thisisatest

This is the quick answer.

To learn other useful string methods in Python, feel free to check this article.

In this guide, we take a look at other common situations related to removing spaces from a string.

In Python, a string is an immutable type. This means it cannot be directly modified. This means any method that manipulates strings actually creates a new string.

In Python, there are many ways you can replace blank spaces:

  1. str.strip[]
  2. str.replace[]
  3. str.join[] with str.split[]
  4. str.translate[]
  5. re.sub[]

Let’s go through each of these options and when you should use them.

1. str.strip[]—Remove Leading and Trailing Spaces

The str.strip[] method removes the leading and trailing whitespace from a string.

For instance:

string = " This is a test "
modified = string.strip[]

print[modified]

Output:

This is a test

2. str.replace[]—Remove All White Spaces

To wipe out all the white spaces from a string, you can use the str.replace[] method.

This method takes two mandatory arguments:

  1. The target strings you want to get rid of.
  2. The string that replaces all the target strings.

In other words, to remove the white spaces, replace each white space with an empty string.

For instance:

string = "This is a test"
modified = string.replace[" ", ""]

print[modified]

Output:

Thisisatest

3. str.join[] and str.split[]—Remove Duplicate White Spaces

To get rid of tabs, newlines, or any other duplicate whitespaces use str.join[] method with str.split[].

This works such that:

  • The str.split[] method splits the string into a list of words without spaces.
  • The str.join[] takes a list of words and joins them using the str as a separator.

For example, let’s remove the duplicate white spaces but leave single white spaces:

before = "This \t is a \n test \n\n  \t let's modify this"
after = " ".join[before.split[]]

print[before]
print[after]

Output:

This     is a 
 test 

         let's modify this


This is a test let's modify this

4. str.translate[]—Remove Tabs, Newlines, and Other White Spaces

To get rid of all the white spaces, tabs, newlines, you can use the str.translate[] method with str.maketrans[] method.

The str.translate[] method replaces strings according to a translation table created by str.maketrans[] method. In short, the str.maketrans[] method works such that it takes three arguments:

  1. A string to be replaced.
  2. A string that specifies the characters to be replaced in the first argument.
  3. A list of characters to be removed from the original string. To remove white spaces, use string.whitespaces, which is a list of the types of blank spaces.

For instance:

import string

before = "This \t is a \n test \n\n  \t let's modify this"

after = before.translate[str.maketrans["", "", string.whitespace]]

print[before]
print[after]

Output:

Thisisatestlet'smodifythis

5. re.sub[]—Replace White Spaces with Empty Strings

RegEx orRegular Expression is like a Ctrl+F on steroids.

You can use it to match patterns in a string. You can for example use regex to find phone numbers or email addresses from a text document.

I am not going to go into more details about regex, but here is a great article you can check.

To use Regular Expressions in Python to remove white spaces from a string:

  1. Import the regex module, re, to your project.
  2. Define a regex pattern that matches white spaces.
  3. Substitute each white space with a blank space using re.sub[] method.

For example:

import re

string = "This is a test"

# Regular expression that matches each white space
whitespace = r"\s+"

# Replace all mathces with an empty string
nospaces = re.sub[whitespace, "", string]

print[nospaces]

Output:

Thisisatest

Conclusion

Today you learned five ways to remove white spaces and duplicate white spaces from Python strings in different situations. Feel free to use the one that best fits your needs!

Thanks for reading. I hope you found an answer to your question.

Happy coding!

Further Reading

50 Python Interview Questions

How do you replace a character with space in Python?

Use str. replace[] to replace underscores with spaces replace[old, new] with an underscore as old and a space as new to replace all underscores with spaces in a string.

How do you replace a character with a space?

Use the replaceAll[] method to replace a character with a space. The method takes the character to be replaced and the replacement string as parameters, e.g. str. replaceAll['_', ' '] . The method returns a new string with all occurrences of the character replaced by the provided replacement.

Can you replace a character in a string Python?

The Python replace[] method is used to find and replace characters in a string. It requires a substring to be passed as an argument; the function finds and replaces it. The replace[] method is commonly used in data cleaning.

Can you replace a character in a list Python?

Python possesses many in-built functions to make programming easy and replace[] method is one of them. replace[] method helps to replace the occurrence of the given old character with the new character or substring.

Chủ Đề