0

I want to assign my image names to another string. Below I have described the problem.

num=[10,20,30,40,50,60,.....500]
for i in range(len(num)):
  img[i]=str(num[i])+'_image_plane_XX_YY.fits' 

so after this loop it should give me,

img0='10_image_plane_XX_YY.fits'
img1='20_image_plane_XX_YY.fits'
....
img499='500_image_plane_XX_YY.fits'

this means, img0 equal the image name of 10_image_plane_XX_YY.fits, img1 equal the image name of 20_image_plane_XX_YY.fits, etc. So I just need to use img0, img1,..for my corresponding images in further analysis. But, when I run this loop, it gives me following error

TypeError: 'str' object does not support item assignment

Please let me know any sollution for this.

Thanks in advance!

Cheers,

-Viral

3 Answers 3

2

For what I think you are trying to do, a list comprehension seems like the more natural approach.

num=[10,20,30,40,50,60]  # I truncated your array for brevity
img = [str(i)+'_image_plane_XX_YY.fits' for i in num]

This will construct img as an array with your assembled strings. For example:

>>> num=[10,20,30,40,50,60]
>>> img = [str(i)+'_image_plane_XX_YY.fits' for i in num]
>>> img[0]
'10_image_plane_XX_YY.fits'
>>> img[3]
'40_image_plane_XX_YY.fits'
Sign up to request clarification or add additional context in comments.

1 Comment

Thanks rchang. That's exactly what I wanted.
0

There's only one reason for this: your img is a string.

This err msg means: strings are immutable, so you can't change their characters in-place.

I think you img should be a list or something similar. Plz check your code.

Comments

0

The problem is in img[i], since you're trying to assign a string to string index and - as the error tells you - strings don't support item assignment.

You can use a dict instead:

img = {}
num=[10,20,30,40,50,60,.....500]
for i in range(len(num)):
   img[i]=str(num[i])+'_image_plane_XX_YY.fits'

So that img becomes:

{ 0:'10_image_plane_XX_YY.fits', 
  1: '20_image_plane_XX_YY.fits',
  ....
  499: '500_image_plane_XX_YY.fits'
}

and you can call images name as:

>>> img[0]
'10_image_plane_XX_YY.fits'

>>> img[1]
'20_image_plane_XX_YY.fits'

However, if you don't need anything other than an integer as key, you should probably use list comprehension as suggested by rchang.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.