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?
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]
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
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]
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.