0

Suppose that I have a list of song names

songlist = np.array(['1.mp3', '2.mp3','3.mp3'])

According to numpy documentation, there's a useful char function called rstrip:

For each element in self, return a copy with the trailing characters removed.

Since the file extension is exactly located in the trailing of the string, so I try using this rstrip to remove the file extensions

np.core.char.rstrip(songlist,'.mp3')

However, it gives me this following output

array(['1', '2', ''], dtype='

What am I doing wrong here? How to use the rstrip function to remove the file extensions correctly?

Raven Cheuk
  • 2,903
  • 4
  • 27
  • 54
  • 1
    `np.rstrip` second parameter `chars` is a set of characters that it removes, thus you will get same result if second parameter was '3pm.' – dgumo Apr 06 '19 at 08:30
  • you can use [endswith or regexp](https://stackoverflow.com/questions/1038824/how-do-i-remove-a-substring-from-the-end-of-a-string-in-python) – harnusek Apr 06 '19 at 08:34

3 Answers3

2

I think numpy is not the best tool for working with strings. I'd use native python, personally.

songlist = np.array(['1.mp3', '2.mp3','3.mp3'])

# extract the part you want with split()
songlist = [s.split('.')[0] for s in songlist]
# could also just slice
# songlist = [s[:-4] for s in songlist]
kevinkayaks
  • 2,636
  • 1
  • 14
  • 30
  • 1
    You could still use the `np.char` functions: `np.vstack(np.char.split(songlist, '.'))[:,0]`. But based on past timings, I don't expect any speed improvements compared to your list comprehension. – hpaulj Apr 06 '19 at 16:44
2

If you want to use numpy string functions:

s = np.array([np.str.rpartition(s,'.mp3')[0] for s in songlist])

You could also look at partition and replace

dgumo
  • 1,838
  • 1
  • 14
  • 18
1

As @dgumo mentioned, rstrip removes characters irrespective of their order. To remove ".mp3" only,

[song.replace('.mp3' , '') for song in songlist]

Or if you are sure the string ends with .mp3

[song[:-4] if song.endswith('.mp3') else song for song in songlist]
harnusek
  • 58
  • 4
user2248259
  • 316
  • 1
  • 3
  • 13