Python Forum

Full Version: One of my exercises is breaking my balls.
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Pages: 1 2
If line == '@1' it's not in your list
if line == '$%' it's not in your list
if line == 'This is my %^$ line' it's not in your list
if line == '@' it is in your list
(Nov-28-2016, 03:19 PM)Jei Wrote: [ -> ]why is it only using "else:?

(Nov-27-2016, 04:03 PM)stranac Wrote: [ -> ]Right now you're checking if a longish string, such as "no2no123non4" is in your list of single character strings.
This will never be the case.
(Nov-28-2016, 02:33 PM)ichabod801 Wrote: [ -> ]Stranac gave you the tips you need.
strings = ("!","@","#","$","%","^","&","*","(",")","_","+","=","-",".",",",")

with open("strings.txt") as f:
    for line in f:
        if any(i in line for i in strings):
            print(line.strip('\n') + " was invalid.")
        else:
            print(line.strip('\n') + " was ok.")
f.close()
Angel
If you're using a with block like that, you don't need to close the file manually.  any() is kind of advanced for where it seems you are, you could also iterate over the contents of the line, like so (normally I don't post answers to questions, but since you already have a working solution, I'll offer some tips):
# ...open file, define invalid chars, etc
for line in input:
    valid = True
    for char in line:
        if char in invalid_characters:
            valid = False
        # or...
        valid = valid and char not in invalid_characters

    if valid:
        print("{0} was ok".format(line))
    else:
        print("{0} was invalid".format(line))
    # or...
    print("{0} was {1}".format(line, "ok" if valid else "invalid"))
(Nov-30-2016, 05:46 PM)nilamo Wrote: [ -> ]If you're using a with block like that, you don't need to close the file manually.  any() is kind of advanced for where it seems you are, you could also iterate over the contents of the line, like so (normally I don't post answers to questions, but since you already have a working solution, I'll offer some tips):
# ...open file, define invalid chars, etc
for line in input:
    valid = True
    for char in line:
        if char in invalid_characters:
            valid = False
        # or...
        valid = valid and char not in invalid_characters

    if valid:
        print("{0} was ok".format(line))
    else:
        print("{0} was invalid".format(line))
    # or...
    print("{0} was {1}".format(line, "ok" if valid else "invalid"))

Thanks for the tips Rolleyes
Pages: 1 2