Regarding Python, beyond my logic

Hope some python experts might be lurking in here to:

Im strugling with some logic.

I want to check a string in a list if a character is present ie. either A or B is there, and return some value.

But the behavior is very strange, Iv included a simplified versin of my script:

arr = [“R”,“M10”,“G”,“P”]
i = 0
t = “”
while i < len(arr):
if “M” or “N” in arr[i]:
t += arr[i]
i += 1
print(t)

But like this it returns RM10GP, all the entries in my array/ list

That screws the logic in my head, I would want it to only return M10?

If I do like this
arr = [“R”,“M10”,“G”,“P”]
i = 0
t = “”
while i < len(arr):
if “M” or “P” in arr[i]:
t += arr[i]
i += 1
print(t)

It also returns RM10GP , what why, theres no M or P in R?

any help would be appriciated :slight_smile:

You can use String.Contains(item) If you want to get string members which contains item you want.

arr = ["R","M10","G","P"]
t = ""
for i in range(len(arr)):
	if arr[i].Contains("M") or arr[i].Contains("P"):
		t += arr[i]
print(t)
1 Like

Whilst @Hyunu_Kim is correct, pure Pythonic strings do not have a builtin function called ‘Contain’ so this method will only work if you are in Dynamo and have called the Revit nodes library like below

import clr 
clr.AddReference("RevitNodes")

If you wanted to do this more concisely and without any dependencies you could use list comprehension and the ‘in’ function (which is essentially the contain function) as below:

sequence = ["R","M10","G","P"]
arg = "0"

t = [i for i in sequence if arg in i]
print(t)

Hope that makes sense

1 Like

@Falk I would make it like that:

arr = ["R","M10","G","P","P0"]
t = ""
for i in range(len(arr)):
	if "M" in arr[i] or "P" in arr[i]:
		t = arr[i]
		print(t)

Edit: as per @haganjake2 suggestion:

sequence = ["R","M10","G","P"]
t = [i for i in sequence if "M" in i or "P" in i]
print(t)
1 Like

This just requires a simple for loop.
image

Print only works for functions. You have to define a variable (or variables) to send to OUT. In this case that would require writing to a list.

1 Like

Hi guys

Thx for all your replies.

@Nick_Boyts solution worked for me :slight_smile:

A small modification:

arr = [“R”,“M10”,“G”,“P”,“P0”]
out = “”
for i in arr:
if “M” in i or “P” in i:
out += “1\n”
print(out)

Result:
1
1
1