0

I have a python list like this:

['photo_1.jpg', 'photo_10.jpg', 'photo_100.jpg' ]

and now I want to remove .jpg from every element in the list and become

['photo_1', 'photo_10', 'photo_100' ]

I have try

for x in list:
    x.replace('.jpg', '')

But it doesn't work. Could anyone help me. Thanks!

kali
  • 117
  • 7
  • @ChristianDean I doubt that'll work for them (given how they disregard the results of expressions). And remember the instruction to "Avoid answering questions in comments". – Kelly Bundy Jul 19 '22 at 15:21
  • @KellyBundy, Not sure what you mean? If they use a list comprehension, they're no longer ignoring the result of the expression, they're using it. And fair enough, give the current state of the StackExchange administration, I find it hard to find the motivation to write out full answers. – Christian Dean Jul 19 '22 at 15:33
  • @ChristianDean I mean they might very well ignore the result of the list comprehension, too. – Kelly Bundy Jul 19 '22 at 15:53
  • I think the main thing before going further is to avoid using `list` as a variable –  Jul 19 '22 at 16:12
  • `.replace` creates a new string, which you don't do anything with. – juanpa.arrivillaga Jul 19 '22 at 16:31

1 Answers1

0

First of all, by every means, you need to prevent using list as a variable because list is already a built-in function in Python. Using it as a variable will eventually cause you more problems in your later coding.

On the other hand, the only thing you need is to make sure you append it into a new variable if you are not doing list comprehension.

newlist = []
for x in list_:
    newlist.append(x.replace('.jpg', ''))
    

newlist
Out[456]: ['photo_1', 'photo_10', 'photo_100']

Or a more complicated way, that is using slicing in your string.

newlist = []
for x in list_:
    newlist.append(x[:-4])