Use converted variable inside a regular expression python 2.6 - python

I tried many diffrent way but not success, i want to use string variable while running re.search function. But if i use a string which is converted from a list member it is not succeeded, if i define a str variable i can do, when check type of variables both of them is str.
mylist=['upl1', 'upl2', 'upl3']
ara_ci=mylist[2]
ara_ci=str(ara_ci)
#if i define it like this , not success
ara_ci='upl3'
#if i define it like this , success
IFAL='list_upl3_other'
if re.search(r'%s' % ara_ci, IFAL):
CLASS='TEST'
else:
CLASS='DEFAULT'

ara_ci=str(ara_ci) is the sytax for type-casting something to str. Note (..) instead of [..].
something[i] is the syntax for accessing ith index of something list OR, value of i key from something dict.
Also, it is not good practice to over-ride python keywords (based on ara_ci=list[3]). list is data-type in Python

Related

How can I make a list that contains various types of elements in Python?

I have the following parameters in a Python file that is used to send commands pertaining to boundary conditions to Abaqus:
u1=0.0,
u2=0.0,
u3=0.0,
ur1=UNSET,
ur2=0.0,
ur3=UNSET
I would like to place these values inside a list and print that list to a .txt file. I figured I should convert all contents to strings:
List = [str(u1), str(u2), str(u3), str(ur1), str(ur2), str(ur3)]
This works only as long as the list does not contain "UNSET", which is a command used by Abaqus and is neither an int or str. Any ideas how to deal with that? Many thanks!
UNSET is an Abaqus/cae defined symbolic constant. It has a member name that returns the string representation, so you might do something like this:
def tostring(v):
try:
return(v.name)
except:
return(str(v))
then do for example
bc= [0.,1,UNSET]
print "u1=%s u2=%s u3=%s\n"%tuple([tostring(b) for b in bc])
u1=0. u2=1 u3=UNSET
EDIT simpler than that. After doing things the hard way I realize the symbolic constant is handled properly by the string conversion so you can just do this:
print "u1=%s u2=%s u3=%s\n"%tuple(['%s'%b for b in bc])

passing fields of an array of collections through functions in python

is there a way of passing a field of an array of collections into a function so that it can still be used to access a element in the collection in python?. i am attempting to search through an array of collections to locate a particular item by comparing it with an identifier. this identifier and field being compared will change as the function is called in different stages of the program. is there a way of passing up the field to the function, to access the required element for comparison?
this is the code that i have tried thus far:
code ...
In your code, M_work is a list. Lists are accessed using an index and this syntax: myList[index]. So that would translate to M_work[place] in your case. Then you say that M_work stores objects which have fields, and you want to access one of these fields by name. To do that, use getattr like this: getattr(M_work[place], field). You can compare the return value to identifier.
Other mistakes in the code you show:
place is misspelled pace at one point.
True is misspelled true at one point.
The body of your loop always returns at the first iteration: there is a return in both the if found == True and else branches. I don't think this is what you want.
You could improve your code by:
noticing that if found == True is equivalent to if found.
finding how you don't actually need the found variable.
looking at Python's for...in loop.

Alternatives for exec to get values of any variable

For debugging purposes I need to know the values of some variables in Python. But, I don't want create a dictionary with all variables and don’t want to add every new variable that I want to test at some point to a dictionary, especially when it comes to lists and their content, which is often procedurally generated.
So is there an alternative to just taking input as a string and then executing it by exec() or using print() and hardcoded variables?
Yes, there is a way. You can use the locals() function to get a dictionary of all variables. For example:
a=5
b=locals()["a"]
Now b will get the value of a, i.e. 5.
However, while you can do this doesn't mean you should do this. There may be something wrong in the structure of your program if you want to access variables by using their name stored in a string.

How to access the keys and values of dictionary passed as argument in method

I have a c# background and I am trying to pass a dictionary in method and some some I want to check if a specific key exists or not. If that key exists in dictionary and then I want to perform few other things.
Let suppose if have following dictionary:
tel = {'jack': 4098, 'sape': 4139}
and I want to check whether key 'sape' exists or not? In method somehow, I do not know the type of argument. How can I cast to dictionary in order to retrieve keys and values.
In method I want to check:
keys = tel.keys () ;
keys.__contains__('sap')
do something
However, in method, I do not have information about the type of passed argument.
Few things to note about Python:
Python is not statically typed like C#. The function/method signature doesn't contain the data types of the parameters. So you do not need to cast the passed in value to a dictionary. Instead you assume that what is passed in is a dictionary and work on it. If you expect that something other than dictionary will be passed you can either use exception handling to catch any issues or you can use isinstance to check what is passed in is what you expect. Having said that casting does exist in python; for example you can convert an int 1 to a string by str(1).
Also note that if use the in keyword it will work for any iterable not just dictionary.
Example:
>>> 'jack' in 'lumberjack'
True
>>> tel = {'jack': 4098, 'sape': 4139}
>>> 'jack' in tel
True
>>>
If you really want to check if something is a dictionary you can do like this:
>>> isinstance(tel,dict)
True

How to ensure list contains unique elements?

I have a class containing a list of strings. Say:
ClassName:
- list_of_strings
I need to enforce that this list of strings contains unique elements. Unfortunately, I can't change this list_of_strings to another type, like a set.
In the addToList(str_to_add) function, I want to guarantee string uniqueness. How can I best do this? Would it be practical to add the string being added to the list, convert to a set, then back to a list, and then reassign that to the object?
Here's the method I need to update:
def addToList(self, str_to_add):
self.list_of_strings.append(str_to_add)
Thanks!
def addToList(self, str_to_add):
if str_to_add not in self.list_of_strings:
self.list_of_strings.append(str_to_add)
Either check for the presence of the string in the list with in, or use a set in parallel that you can check and add to.
You indeed could do the list-to-set-to-list operation you described, but you could also use the in operator to check if the element is already in the list before appending it.
One possible way to do this would be to create a hash set and iterate through the list, adding the elements to the set; a second iteration could be used to remove any duplicates.
Perhaps we can do like this:
def addToList(self, str_to_add):
try:
self.list_of_strings.index(str_to_add)
except:
self.list_of_strings.append(str_to_add)
Well, I don't know whether it's the same mechanism with if/else yet.

Categories

Resources