So my question is:
I will have an array. which contains ["something.json", "something2.json", "something3.json"]
.
I want to remove every .json in this array and get an output which is similar to like ["something", "something2", "something3"]
using Python. Thanks for helping me out.
Asked
Active
Viewed 324 times
-1

Mr. Noobcrafter
- 21
- 1
- 1
-
Do you want to strip file extensions? or just anything after the first dot? or anything after the last dot? What is your expected output for `anything.json.json`? – Chris Feb 05 '21 at 05:24
-
`print([x.replace(".json", "") for x in ["something.json", "something2.json", "something3.json"]])` – D. Seah Feb 05 '21 at 05:24
-
This isn't particularly difficult to do. Have you tried out something that didn't work? If so, post it so we can help explain you where you went wrong, and ways to improve/fix it. – costaparas Feb 05 '21 at 05:25
-
[I think this question is already answered here](https://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python) Hope this helps! – Minjin Gelegdorj Feb 05 '21 at 05:27
-
[I think this question is already answered here](https://stackoverflow.com/questions/3939361/remove-specific-characters-from-a-string-in-python) Hope this helps! – Minjin Gelegdorj Feb 05 '21 at 05:28
-
@Chris I want to remove the file extensions. – Mr. Noobcrafter Feb 05 '21 at 05:29
1 Answers
1
You can use .endswith()
to find the elements that have that file type and then slice everything except the suffix.
my_list = ["something.json", "something2.json"]
suffix = ".json"
my_list = [x[:-len(suffix)] for x in my_list if x.endswith(suffix)]
If you are using python3.9 you could use new string method to remove the suffixes
str.removesuffix(suffix, /): If the string ends with the suffix string and that suffix is not empty, return string[:-len(suffix)]. Otherwise, return a copy of the original string:
>>> 'MiscTests'.removesuffix('Tests')
'Misc'

BeanBagTheCat
- 435
- 4
- 7
-
For the record, the first method isn't that great. You have to "manually" work out how many characters there are in the suffix you want to remove and update that if ever you want to change the suffix to remove. – costaparas Feb 05 '21 at 05:43
-
@costaparas thats true but i feel its easily solvable with variables. Ill change the answer to include an example with variables. – BeanBagTheCat Feb 05 '21 at 05:49