2

I'm trying to take input as:

1.jpg 10.png 11.png 2.jpg 3.png

and print out to a list by using lambda expression:

['001.jpg', '010.png', '011.png', '002.jpg', '003.png']

files = input().split()

print(list(map('{0:03d}.{1}'.format(lambda x: int(x.split('.')[0]), x.split('.')[1], files))))

I thought I did it right. But it occurs an error as: AttributeError: 'list' object has no attribute 'split'

What am I missing?

4
  • show the error. Commented Oct 26, 2019 at 4:13
  • @hpaulj AttributeError: 'list' object has no attribute 'split' Commented Oct 26, 2019 at 4:16
  • You can split a string into a list of strings. Make sure you understand what each variable is. Commented Oct 26, 2019 at 4:27
  • I'm not able to get your error. My error indicates that passing a lambda function as an argument to format is not allowed. The answer given by @Ofer Sadan is very elegant, you should use it. Since you want to know what you missed I sugest to look at this way of doing it print (list (map(lambda x : '{0:03d}.{1}'.format(int(x.split('.')[0]), x.split('.')[1]), files) )) Commented Oct 26, 2019 at 4:43

3 Answers 3

3

You don't need any map or lambda, just zfill:

print([x.zfill(8) for x in input().split()])

Adjust 8 in this example to whatever length you need

Sign up to request clarification or add additional context in comments.

1 Comment

Didn't even think of zfill nice answer!
2

You can use simple str.split and calculate the padding from the length of the digit as a string:

s = '1.jpg 10.png 11.png 2.jpg 3.png'
result = list(map(lambda x:'0'*(3-len(x.split('.')[0]))+x, s.split()))

Output:

['001.jpg', '010.png', '011.png', '002.jpg', '003.png']

1 Comment

Can you help me out on my code as well? I just want to know what I'm missing
1

A list comprehension is more efficient here than map and lambda and way more readable.

s = '1.jpg 10.png 11.png 2.jpg 3.png'
result = ['{0:0>3}.{1}'.format(*x.split('.')) for x in s.split()]

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.