Avoid using the same functions twice

Viewed 96

I have two outputs of two commands (it doesnt matter the content, the thing is that I have to replace for both the same characters):

string1 =  str(newstring1).replace("\\r", "").replace("  ", "").replace("\\", "").replace("' ", "").replace("\n", ", ").replace("MB ", "MB").replace("MB", "MB ")
string2 = str(newstring2).replace("\\r", "").replace("  ", "").replace("\\", "").replace("' ", "").replace("\n", ", ").replace("MB ", "MB").replace("MB", "MB ")

That works, but my question is, Is there any way to do those "replaces" just once? Instead of doing this two times.

I tried creating a variable with .replace("\\r", "\n").replace("[", "").replace("'", "").replace(" ", "").replace(",", "").replace("]", "").replace("\n ", "\n").rstrip().lstrip().replace("MB ", "MB").replace("MB", "MB ") but it does not work.

3 Answers

Write a custom function and call it for all your strings.

def replace_all(s):
    return s.replace("\\r", "").replace("  ", "").replace("\\", "").replace("' ", "").replace("\n", ", ").replace("MB ", "MB").replace("MB", "MB ")

string1 = replace_all(newstring1)
string2 = replace_all(newstring2)

You can probably use re.sub to combine some of your logic

import re
re.sub(r"MB\s*", "MB ", s)

you can concatenate the strings with a separator that does not appear in any of them. Run the replacement and then separate them again

new_combined_string = newstring1 + "#" + newstring2
combined_string = str(new_combined_string).replace("\\r", "").replace("  ", "").replace("\\", "").replace("' ", "").replace("\n", ", ").replace("MB ", "MB").replace("MB", "MB ")
strings = combined_string.split("#")
string1 = strings[0]
string2 = strings[1]
Related