2
$\begingroup$

I'm new to python. For learning I'm trying to create a script to find a character "ä" or "." etc in all selected objects; and select only those objects.

Here is my code:

for obj in bpy.context.selected_objects:
    if "." in obj.name: #how can i add more additional character e.g. space?
        print("script found space or points")
        #how do select this objects?

    else:
        print("names all right")
$\endgroup$
1
  • $\begingroup$ If you ever want more complex searches look at the re module $\endgroup$
    – sambler
    Commented Nov 30, 2016 at 5:29

2 Answers 2

3
$\begingroup$
import bpy

params = [".", "ä" ] #add your list of search parameters

for obj in bpy.context.selected_objects:
    if any(x in obj.name for x in params): #search for params items in object name
        print("script found space or points") #do nothing else since object is already selected
    else:
        print("names all right")
        obj.select = False # deselect object

https://docs.python.org/3/library/functions.html#any

$\endgroup$
4
$\begingroup$

Ok first try to think what you really want to do. You are trying to select some object based on its name, however you are looking at the selected objects.
So what you really want to do, is unselect everything else (because the object(s) you do want is already selected).

Here is a loop that goes through every selected object bpy.context.selected_objects:, and if the search term does not match the current object name it deselects it. Which leaves you with only the matching objects selected.

import bpy
searchTerm = "cube"
for obj in bpy.context.selected_objects:
    if searchTerm.lower() not in obj.name.lower():
        obj.select = False

The .lower() part converts everything to lower case, which makes the search case insensitive (if you did not "c" would not match "Cube").


Now one way you could search for more then one search term at a time, is to add in a or into the if statement.
Which would look like this:

if "a" not in obj.name.lower() or " " not in obj.name.lower():

Note the second condition " ", that is searching for a space in the object name.


Here is a slightly more useful version that looks through all the objects, selects the matching objects and deselects any that do not match.

import bpy

for obj in bpy.data.objects:
    if "s" in obj.name.lower():
        obj.select = True
    else:
        obj.select = False
$\endgroup$

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .