QBoard » Artificial Intelligence & ML » AI and ML - R » Removing Two Characters From A String

Removing Two Characters From A String

  • Related question here.
    So I have a character vector with currency values that contain both dollar signs and commas. However, I want to try and remove both the commas and dollar signs in the same step.
    This removes dollar signs =
    d = c("$0.00", "$10,598.90", "$13,082.47") gsub('\\$', '', d)
    This removes commas =
    library(stringr) str_replace_all(c("10,0","tat,y"), fixed(c(","), "")
    I'm wondering if I could remove both characters in one step.
    I realize that I could just save the gsub results into a new variable, and then reapply that (or another function) on that variable. But I guess I'm wondering about a single step to do both.
      December 3, 2021 10:40 AM IST
    0
  • Since answering in the comments is bad:

    gsub('\\$|,', '', d)
    


    replaces either $ or (|) , with an empty string.


      December 4, 2021 1:14 PM IST
    0
  • Create a copy of the original string. Put the multiple characters that will be removed in one string. Use a for-loop to iterate through each character of the previous result. At each iteration, call str.replace(old, new) with old as the character and new as "" to replace old with new in the copy of the original string. Then, assign the copy of the original string to be the previous result.

    original_string = "!(Hell@o)"
    characters_to_remove = "!()@"
    
    new_string = original_string
    for character in characters_to_remove:
      new_string = new_string.replace(character, "")
    
    print(new_string)
    OUTPUT
    Hello
    ​
      December 8, 2021 10:23 AM IST
    0
  • Use str. replace() to remove multiple characters from a string
    1. original_string = "!( Hell@o)"
    2. characters_to_remove = "!()@"
    3. new_string = original_string.
    4. for character in characters_to_remove:
    5. new_string = new_string. replace(character, "")
    6. print(new_string)
      December 9, 2021 12:37 PM IST
    0
  • Removing characters from a string in Python can be most useful in many applications. Filter texts, sentiments always require the main method and solution of being able to delete a character from a string.

    • You can easily remove a character from a string using replace() and translate() method.
    • To remove a character from a string there are many ways to solve this.
    • we will discuss the following approaches.
      • Using the Python replace() method
      • Using the translate() method
      • Using slicing method
      • Using join() method
      • Using filter() method
      December 15, 2021 12:32 PM IST
    0