0

Good day, I need to remove apostrophes from a string that is being used to create a file. It causes an error because file names cant contain apostrophes. I read through other questions on stack overflow and some people are saying to use: string.replace("'", "") I tried that but it doesn't remove the apostrophe. Here is the code I'm running:

download_url = f'{result["link"]}'
song_name = f'{result["title"]}'
status = f'{result["status"]}'
correct_song_name = song_name.replace("'", "")
save_location = download_location()
urllib.request.urlretrieve(download_url, save_location + 
correct_song_name + '.mp3')

Here is an example of what happens when it is fed a title with apostrophes: OSError: [Errno 22] Invalid argument: 'C:/Users/Jonathan/Desktop/Test2/What is "this".mp3'

What am I doing wrong or what are the other ways of removing characters from the string?

  • [This question](https://stackoverflow.com/questions/7406102/create-sane-safe-filename-from-any-unsafe-string) might be useful. – Matt Hall Nov 03 '21 at 13:21
  • Please be aware that "apostrophe" would normally be understood to refer to single quotes, whereas the character that you are trying to remove is double quotes. – alani Nov 03 '21 at 13:23

1 Answers1

1

Your current code only removes single quotes and not double quotes. The following would remove the correct character:

correct_song_name = song_name.replace('"', "")

If you have both single and double quotes, you can use:

correct_song_name = song_name.replace('"', "").replace("'", "")
nbeuchat
  • 6,575
  • 5
  • 36
  • 50