Jonathan Langford
Jonathan Langford

Reputation: 19

Remove apostrophe from string in python

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?

Upvotes: 0

Views: 966

Answers (1)

nbeuchat
nbeuchat

Reputation: 7091

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("'", "")

Upvotes: 1

Related Questions