简体   繁体   中英

How do I check whether an input string has alphabets in another string in Python?

As the title says, how do I check whether an input string has alphabets in another string in Python?

The string specifies that only alphabets A to G ('ABCDEFG') can be used in the input string. However, my attempt did not get the results I want. Instead, input strings with alphabets in order such as 'ABC' and 'ABCD' work, while those not in order such as 'BADD' and 'EFEG' do not.

Please refer to my attempt below.

ID = 'ABCDEFG'
addcode=input('Enter new product code: ')
Code = []

if addcode in ID:
    Code.append(addcode)
    print(Code)
else:
    print("Product code is invalid")

Ideally, as long as the input string contain letters from A to G, it should be appended to 'Code' regardless of the order. How do I modify my code so that I can get the results I want? Thank you.

You can use RegEx:

re.search('[a-zA-Z]', string)

You can try converting your input string (addcode) to a set and then see if it is a subset of ID. I am not converting ID into a set as it contains unique elements as per your code:

ID = 'ABCDEFG'
addcode = input('Enter new product code: ')
Code = []

if set(addcode).issubset(ID):
    Code.append(addcode)
    print(Code)
else:
    print("Product code is invalid")

If you want to use a RegEx based approach, you can do this:

import re

pattern = re.compile("^[A-G]+$")
addcode = input('Enter new product code: ')
Code = []

if pattern.findall(addcode):
    Code.append(addcode)
    print(Code)
else:
    print("Product code is invalid")

We are checking if the input string contains only characters between A-G here ie A,B,C,D,E,F,G. If there is a match, we append the input string and print it.

String is immutable. You should check whether each letter of product code is present in the ID.

To achieve this you can use ID as tuple instead of single string.

ID = ('A','B','C','D','E','F','G')

addcode=input('Enter new product code: ')
Code = []
for l in range(0,len(addcode)):
    if addcode[l] in ID:
        Code.append(addcode[l])

    else:
        print("Product code is invalid")

print(Code)

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