0

i have a code that take the music title of xbmc and i want to put it in a url to send it. However urllib does not like the space in the title here the code:

 if xbmc.Player().isPlayingAudio() and audio != 1 :
    audio = 1
    urllib2.urlopen('http://%s:3480/data_request?id=variableset&DeviceNum=%s&serviceId=urn:upnp-org:serviceId:XBMCState1&Variable=PlayerStatus&Value=playing_audio' % (ip, dev)) 
    tag = xbmc.Player().getMusicInfoTag()
    title = tag.getTitle()
    title.replace(" ", "_")
    print ("playing:" + title)

however when check in the log file, the space still there. All i want is (title = summer of 69) to (title = summer_of_69) and if possible convert also the (') to nothing

Thanks Mic

2 Answers2

3

str.replace isn't an inplace operation - since strings are immutable, it returns a new string, so you need to assign afterwards. title = title.replace(' ', '_')

Alternatively, just change your print to: print('playing:', title.replace(' ', '_'))

And if you only want certain characters, then you could do something like:

>>> import re
>>> track = "summer       of      '69"
>>> re.sub('[^a-z0-9]+', '_', track, re.I)
'summer_of_69'

Which takes anything that isn't an ascii letter, a digit and scrunches them into a single '_'.

Jon Clements
  • 138,671
  • 33
  • 247
  • 280
  • thanks it work, if i will like to also remove the ' character, do i need to make a other line or i could add it in this conversion and thanks for your super fast responce. – user2052746 Feb 08 '13 at 22:56
  • Almost sounds like you want to filter valid characters rather than ones you don't want, but yeah just, `title.replace(' ', '_').replace("'", '')` – Jon Clements Feb 08 '13 at 22:58
0

Try this:

title = title.replace(" ", "_")

title.replace() doesn't replace the text in the original string, it creates a new string which is equal to the original string, with the replacement. All you have to do is take the returned value of that method, and put it in the place of the original variable.

KebertX
  • 304
  • 1
  • 6