0

Python newbie here, I'm trying to search a video API which, for some reason won't allow me to search video titles with certain characters in the video title such as : or |

Currently, I have a function which calls the video API library and searches by title, which looks like this:

def videoNameExists(vidName):
    vidName = vidName.encode("utf-8")
    bugFixVidName = vidName.replace(":", "")
    search_url ='http://cdn-api.ooyala.com/v2/syndications/49882e719/feed?pcode=1xeGMxOt7GBjZPp2'.format(bugFixVidName) #this URL is altered to protect privacy for this post

Is there an alternative to .replace() (or a way to use it that I'm missing) that would let me search for more than one sub-string at the same time?

AdjunctProfessorFalcon
  • 1,790
  • 6
  • 26
  • 62

1 Answers1

2

Take a look a the Python re module, specifically at the method re.sub().

Here's an example for your case:

import re

def videoNameExists(vidName):
    vidName = vidName.encode("utf-8")
    # bugFixVidName = vidName.replace(":", "")
    bugFixVidName = re.sub(r'[:|]', "", vidName)
    search_url ='http://cdn-api.ooyala.com/v2/syndications/49882e719/feed?pcode=1xeGMxOt7GBjZPp2'.format(bugFixVidName) #this URL is altered to protect privacy for this post
Matt
  • 902
  • 7
  • 11
  • Thanks a lot for the example! Can you breakdown what the `r` in `(r'[:|]', "", vidName) ` does? I was reading in the documentation that "Unless an 'r' or 'R' prefix is present, escape sequences in strings are interpreted according to rules similar to those used by Standard C" - is that why we need `r` there? – AdjunctProfessorFalcon Jun 28 '15 at 04:09
  • In this case the `r` wasn't really necessary because none of the characters need to be escaped, but in general its use simplifies the use of strings for writing regular expressions. Take a look at [this question](http://stackoverflow.com/questions/2241600/python-regex-r-prefix), in my opinion [the second answer](http://stackoverflow.com/a/2241641/504273) has a good practical example. – Matt Jun 28 '15 at 06:55