0

How can I delete the following characters in a string: '.SW'. Characters to remove are '.SW' in the following example:

stock = 'RS2K.SW'
original_string = stock
characters_to_remove = ".SW"
new_string = original_string
for character in characters_to_remove:
   new_string = new_string.replace(character, "")
stocketf = new_string
print (stocketf)

Result should be: RS2K

My actual wrong result is: R2K

jezrael
  • 822,522
  • 95
  • 1,334
  • 1,252
Yvar
  • 155
  • 4
  • 14
  • you can directly replace the full substring: `new_string = stock.replace(characters_to_remove, "")`, with current approach, every occurrence of `S` is getting removed. – Krishna Chaurasia Apr 08 '21 at 09:43

3 Answers3

1

In this case, it looks like that you could just remove the last three characters.

my_str = my_str[:-3]

Otherwise, I would suggest using Regex

CrazyHorse
  • 53
  • 6
1

There are a few ways to choose from as the existing answers demonstrate. Another way, if these characters always come at the end, could be to just split your string on the '.' character and keep the first section:

stock = 'RS2K.SW'
new_string = stock.split(.)[0]
acrobat
  • 812
  • 4
  • 7
0

In this case this should be a valid solution for your answer:

stock = 'RS2K.SW'
original_string = stock
characters_to_remove = ".SW"
new_string = 
stock[:original_string.index(characters_to_remove)]
print(new_string)