jmat
jmat

Reputation: 1

Cant append items to a list using conditionals

So I am trying to append items to various lists based on .isdigit() as a conditional as well as the presence of a string...

For example:

h="hello"

if h.isdigit()==False and "hello" in h:
    print(h)

hello

^This is valid..

However, when I try to incorporate this-

The following is valid:

user = "jerry"
names = ['max1','max2','jerry1','jerry2','jerry3','steph1','steph2','steph3',"susanB","susanC"]
max = []
jerry = []
steph = []
susan = []

for name in names:
    if user in name:
        for char in name:
            if char.isdigit() and "jerry" in name:
                jerry.append(name)

print(jerry)

['jerry1', 'jerry2', 'jerry3']

But not:

user = "jerry"
names = ['max1','max2','jerry1','jerry2','jerry3','steph1','steph2','steph3',"susanB","susanC"]
max = []
jerry = []
steph = []
susan = []

for name in names:
    if user in name:
        for char in name:
            if char.isdigit()==False and "susan" in name:
                susan.append(name)

print(susan)

[]

Expected:

['susanB','susanC']

Can someone please explain what is causing this behavior and how to rectify it?

Upvotes: 0

Views: 47

Answers (2)

Bialomazur
Bialomazur

Reputation: 1141

The answer above already explains what the solution is, but I would like to provide a concrete code implementation of it combined with removing some redundant code pieces.

user = "susan" # You forgot to change this variable.
names = [
    "max1",
    "max2",
    "jerry1",
    "jerry2",
    "jerry3",
    "steph1",
    "steph2",
    "steph3",
    "susanB",
    "susanC",
]
max = []
jerry = []
steph = []
susan = []

for name in names:
    if user in name:
        for char in name:
            if char.isdigit():
                break

        susan.append(name)

print(susan) # Output: ['susanB', 'susanC']

Upvotes: 0

Lemon Reddy
Lemon Reddy

Reputation: 637

You forgot to change the name variable in the beginning. Change it to susan and desired about will be obtained.

The current program is essentially appending items if both jerry and susan are present in the string.

Upvotes: 1

Related Questions