简体   繁体   中英

Check a list contains given elements

I want to check if my list's first four elements are digits. what i did is as follows:

myList = ['0', '3', '2', '7', 'O', 'K', 'P']
if myList[0:4] in string.digits:
  print('okay')
else:
  print('wrng')

But this gives the following error.

TypeError: 'in <string>' requires string as left operand, not list

How can I achieve this?

The error is telling you that you can't do some_list in some_string - after all, a list consists of characters, not lists, so it's pointless. You want to check if all the characters in your list are in the string, so:

if all(ch in string.digits for ch in myList[:4]):

The 0 in 0:4 is not needed, it's the default.

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