1

I am scraping data from a dictionary and the returned data is H or A. In my for loop it is referred to as home_away = stats['home_away'].

I changed the string name to h_a = home_away.replace("A","@")

That works fine, but I also want to change H to " ". Would I do a if statement or a for loop for that?

I tried

if home_away == "H":
   home_away.replace("H"," ")
elif home_away == "A":
   home_away.replace("A","@")
jpp
  • 159,742
  • 34
  • 281
  • 339
Michael T Johnson
  • 679
  • 2
  • 13
  • 26

3 Answers3

3

If the value is only a single character, why are you bothering with .replace() at all? Just reassign the whole thing.

if home_away == "H":
   home_away = " "
elif home_away == "A":
   home_away = "@"
John Gordon
  • 29,573
  • 7
  • 33
  • 58
2

One character replacement

If your input strings are either H or A, i.e. one character, I recommend you use a dictionary:

mapper = {'H': ' ', 'A': '@'}
home_away = mapper[home_away]

Multiple character replacement

If you have multiple characters to replace, you can chain str.replace calls:

home_away = home_away.replace('H', ' ').replace('A', '@')

Alternatively, you can use a mapper dictionary as above with str.translate and str.maketrans:

home_away = 'HAAAH'
home_away = home_away.translate(str.maketrans(mapper))

print(res)
" @@@ "
cs95
  • 379,657
  • 97
  • 704
  • 746
jpp
  • 159,742
  • 34
  • 281
  • 339
1

Not sure what you exactly want, but an easy solution is to not use any if or else conditions and to simply just use:

h_a = home_away.replace("H"," ").replace("A","@");

This solution would ensure that any H character will be replaced with " " and any A character will be replaced with @. If there are no matches, then it would not throw any errors, instead it would retain the existing values stored within the variable and continue to run your script. .

SShah
  • 1,044
  • 8
  • 19