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?
CodePudding user response:
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.
CodePudding user response:
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']