简体   繁体   中英

#How to Filter the palindrome numbers in the given tuple and save it in the tuple

How to Filter the palindrome numbers in the given tuple and save it in the tuple?

My code:

w = (10,11,12,21,22,101,123,111,152)

for i in w:
    if i[:]==i[-1:]:
        print(i)

Error : TypeError                                 Traceback (most recent call last)
<ipython-input-143-b2b3cfdef377> in <module>
      7 
      8 for i in w:
----> 9     if i[:]==i[-1:]:
     10         print(i)

TypeError: 'int' object is not subscriptable

Convert your integer to a string. Also, you weren't using the inverse slicing of the string correctly

w = (10,11,12,21,22,101,123,111,152)

for i in w:
    if str(i) == str(i)[::-1]:
        print(i)

Output:

11
22
101
111

You also mention that you want to save the result in a tuple. Use a generator expression for that:

tuple(i for i in w if str(i) == str(i)[::-1])

Output:

(11, 22, 101, 111)

You cannot use indices for integer values.

  1. i[:] does not work.
  2. str(i)[:] works.

Also str(i)[:] is the same thing with str(i) and str(i)[-1:] only takes the last digit of the number.

If you want to get the number reversed you have to use str(i)[::-1] .

This should work just fine:

w = tuple(i for i in w if str(i) == str(i)[::-1])
print(w)

Check this for a better understanding of the slicing operator:

Try This Code:

w = (10,11,12,21,22,101,123,111,152)
for i in w:
    if str(i)[:]==str(i)[::-1]: 
        print(i)

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM