LinuxQuestions.org

LinuxQuestions.org (/questions/)
-   Programming (https://www.linuxquestions.org/questions/programming-9/)
-   -   Python variable type (https://www.linuxquestions.org/questions/programming-9/python-variable-type-773991/)

MTK358 12-07-2009 09:09 AM

Python variable type
 
I wonder how to know if a variable in Python is a number, list, or string?

Hko 12-07-2009 10:07 AM

Code:

>>> a = [5]
>>> b = "5"
>>> c = 5

>>> type(a)
<type 'list'>

>>> type(b)
<type 'str'>

>>> type(c)
<type 'int'>

>>> if isinstance(a, list): print "Yes, it is a list!"
...
Yes, it is a list!


MTK358 12-07-2009 10:10 AM

I thought that Python doesn't tell any difference between int and float!?

Also, I wonder how to split a string into a list of words, and how to check if a variable does not equal any one of the contents of a list?

David1357 12-07-2009 11:02 AM

Quote:

Originally Posted by MTK358 (Post 3782840)
I thought that Python doesn't tell any difference between int and float!?

Python would disagree with you:
Code:

C:\>python
Python 2.6.2 (r262:71605, Apr 14 2009, 22:40:02) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> 5 / 6
0
>>> 5.0 / 6.0
0.83333333333333337
>>>


bgeddy 12-07-2009 02:49 PM

Quote:

Also, I wonder how to split a string into a list of words, and how to check if a variable does not equal any one of the contents of a list?
Code:

mylist="This is a string to split".split()
is_in_list="unique" in mylist
print "unique is in mylist=",mylist,is_in_list


ghostdog74 12-07-2009 05:53 PM

and finally, head down to the Python documentation site, (my sig) to learn all about it.

Hko 12-08-2009 04:11 AM

Quote:

Originally Posted by MTK358 (Post 3782840)
Also, I wonder how to split a string into a list of words, and how to check if a variable does not equal any one of the contents of a list?

When you were looking for how to split a string, I wonder how did you manage not to find the "split" method of a string in the docs?

Code:

>>> someString = "aap noot mies wim zus jet teun"
>>> someList = someString.split()
>>> type(someList)
<type 'list'>
>>> someList
['aap', 'noot', 'mies', 'wim', 'zus', 'jet', 'teun']
>>> if "zus" in someList: print "Yes, it is in the list!"
...
Yes, it is in the list!



All times are GMT -5. The time now is 08:08 PM.