I am a novice user trying to add a section to an existing script that reads a CSV, and makes changes before outputting a new CSV.
I am trying to add a section that replaces a list of characters that are not acceptable in a specific field for each row in the CSV.
The rule is simple :
“*” should be replaced with “x”
“<” should be replaced with “–”
“>” should be replaced with “–”
“%” should be replaced with “–”
Therefore, I have written the following:
bad_characters = ["*","<",">","%",]
for bad_character in bad_characters:
if bad_character in row["Supplier Catalog Number"]:
if bad_character = "*":
row["Supplier Catalog Number"].replace("*","x")
else:
row["Supplier Catalog Number"].replace(bad_character,"-")
Would this work? Can you use a variable as an argument in a replace function?
@dan.everitt Hello, welcome to the forum. I see some issues in your code.
You have too many commas in the bad_characters list. You need to use the replace method on a string. What error message are you getting?
Thanks for your responses, they gave my the chance to think about some of the specifics of my code.
After some further research I was able to confirm that csv fields are considered as strings by default so my replace function would work. There were some other issues that I needed to figure out that I had missed, like the fact that I needed to write my replaced field somewhere, and that I had used a single “=” rather than “==” in line 5.
Anyway, long story short, I have now got a working code:
bad_characters = ["*","<",">","%",]
for bad_character in bad_characters:
if bad_character in row["Supplier Catalog Number"]:
if bad_character == "*":
row["Supplier Catalog Number"] = row["Supplier Catalog Number"].replace("*","x")
else:
row["Supplier Catalog Number"] = row["Supplier Catalog Number"].replace(bad_character,"-")
Also @brandon_wallace I took note of your comment about the commas in the list, however, I prefer to leave an extra comma in as it makes it easier to add items to the list in future
Thanks to both of you for taking the time to help!