Python .findall() differing behavior [duplicate] - python

Consider this input in a text file:
foo
bar
foobar
If I look in python API for the re package I understand that if I want to match the foo and not the foobar I understand that this code should do it
import re
code = open ('play.txt').read()
print code
print re.findall('^foo$',code)
However the output reads
Python 2.7.12 (default, Dec 4 2017, 14:50:18)
[GCC 5.4.0 20160609] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import play
foo
bar
foobar
[]
>>>
Why?

You need to add re.MULTILINE to your flags.
s = '''foo
bar
foobar'''
re.findall('^foo$', s, flags=re.MULTILINE)
Out[14]: ['foo']

Related

Python: What's the difference between "import X" and "from X import *"? [duplicate]

This question already has answers here:
Use 'import module' or 'from module import'?
(23 answers)
Closed 5 years ago.
I use to think both are equal until I tried this:
$python
Python 2.7.13 (default, Dec 17 2016, 23:03:43)
[GCC 4.2.1 Compatible Apple LLVM 8.0.0 (clang-800.0.42.1)] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import Tkinter
>>> root=Tk()
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
NameError: name 'Tk' is not defined
>>> from Tkinter import *
>>> root=Tk()
So what's the core difference between these 2 kinds of import that import everything from a module?
Thanks.
when you import x , it binds the name x to x object , It doesn't give you the direct access to any object that is your module, If you want access any object you need to specify like this
x.myfunction()
On the other side when you import using from x import * , It brings all the functionalities into your module, so instead of x.myfunction() you can access it directly
myfunction ()
for example lets suppose we have module example.py
def myfunction ():
print "foo"
Now we have the main script main.py , which make use of this module .
if you use simple import then you need to call myfunction() like this
import example
example.myfucntion()
if you use from, you dont need to use module name to refer function , you can call directly like this
from example import myfunction
myfunction()

Python interpreter not working with imported modules?

Ok. So I have a bunch of functions I wrote out in my text editor under functions.py
When I import functions.py into my python interpreter, it tells me that everything I have saved under my functions.py file is not defined.
for example, I have a variable in functions.py called color.
color = "Red"
When I go to print out color in my interpreter, it says that "color is not defined."
Why is it that my interpreter is not remembering my functions or my variables, even though I was able to import the file?
Did you do it like this?:
> cat functions.py
colors = 'red'
> python
Python 2.7.6 (default, Mar 22 2014, 22:59:56)
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> from functions import *
>>> colors
'red'
>>>
First, lunch the interpreter in the same folder of your script then you have to way to call color
1
import functions
print functions.color
2
from functions import color
print color
for both you get printed color value
I found the problem. The following code would have worked if 'color' was not inside a class.
import functions
print functions.color
But because the variable color was inside a class named 'colors' I had to also define 'colors' for the interpreter to pick it up.
import functions
print functions.colors.color
Red

Python 2.7 print() error

I have a strange error using sep, file, (etc.) arguments of python's print() function.
I tried to google it out, dag around stackoverflow, and read python's documentation but I came up with nothing.
I have attached a simple snippet, I would deeply appreciate any help.
# python
Python 2.7.2 (default, Aug 19 2011, 20:41:43) [GCC] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> print("blah"*10, sep=" | ")
File "<stdin>", line 1
print("blah"*10, sep=" | ")
^
SyntaxError: invalid syntax
Try:
from __future__ import print_function
first
In the 2.x series, print is a statement, while in 3.x it's a function. If you want in 2.6+ to have print as a function, you use from __future__ import print_function as the first import statement.
Expect code to break though
The print function is specific to Python 3.
You have two solutions here:
Write
from __future__ import print_function
so you can use it as specified by cdarke.
Or you use print as a simple statement as it should be with older versions of Python (print "Hello World").

How do I pickle an object?

Here is the code I have:
import pickle
alist = ['here', 'there']
c = open('config.pck', 'w')
pickle.dump(alist, c)
and this is the error I receive:
Traceback (most recent call last):
File "C:\pickle.py", line 1, in ?
import pickle
File "C:\pickle.py", line 6, in ?
pickle.dump(alist, c)
AttributeError: 'module' object has no attribute 'dump'
whats going on? I am using python 2.4 on windows xp
Don't call your file pickle.py. It conflicts with the python standard libary module of the same name. So your import pickle is not picking up the python module.
The code you have works fine for me.
Python 2.5.4 (r254:67916, Dec 23 2008, 15:10:54) [MSC v.1310 32 bit (Intel)] on
win32
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>>
>>> alist = ['here', 'there']
>>> c = open('config.pck', 'w')
>>>
>>> pickle.dump(alist, c)
>>>
The issue is that your filename "pickle.py" is making the import pickle statement try to import from your own file instead of the main library. Rename your code file.
Your script is called pickle and therefore shadows the module picke from the standard library. It imports itself and tries to call its dump function (and of course it doesn't have one).
Note that you're "lucky" that you don't get kicked into an infinite import loop (because importing the same module twice just creates another reference to the same module object in memory).

Random in python 2.5 not working?

I am trying to use the import random statement in python, but it doesn't appear to have any methods in it to use.
Am I missing something?
You probably have a file named random.py or random.pyc in your working directory. That's shadowing the built-in random module. You need to rename random.py to something like my_random.py and/or remove the random.pyc file.
To tell for sure what's going on, do this:
>>> import random
>>> print random.__file__
That will show you exactly which file is being imported.
This is happening because you have a random.py file in the python search path, most likely the current directory.
Python is searching for modules using sys.path, which normally includes the current directory before the standard site-packages, which contains the expected random.py.
This is expected to be fixed in Python 3.0, so that you can't import modules from the current directory without using a special import syntax.
Just remove the random.py + random.pyc in the directory you're running python from and it'll work fine.
I think you need to give some more information. It's not really possible to answer why it's not working based on the information in the question. The basic documentation for random is at:
https://docs.python.org/library/random.html
You might check there.
Python 2.5.2 (r252:60911, Jun 16 2008, 18:27:58)
[GCC 3.3.4 (pre 3.3.5 20040809)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> random.seed()
>>> dir(random)
['BPF', 'LOG4', 'NV_MAGICCONST', 'RECIP_BPF', 'Random', 'SG_MAGICCONST', 'SystemRandom', 'TWOPI', 'WichmannHill', '_BuiltinMethodType', '_MethodType', '__all__', '__builtins__', '__doc__', '__file__', '__name__', '_acos', '_ceil', '_cos', '_e', '_exp', '_hexlify', '_inst', '_log', '_pi', '_random', '_sin', '_sqrt', '_test', '_test_generator', '_urandom', '_warn', 'betavariate', 'choice', 'expovariate', 'gammavariate', 'gauss', 'getrandbits', 'getstate', 'jumpahead', 'lognormvariate', 'normalvariate', 'paretovariate', 'randint', 'random', 'randrange', 'sample', 'seed', 'setstate', 'shuffle', 'uniform', 'vonmisesvariate', 'weibullvariate']
>>> random.randint(0,3)
3
>>> random.randint(0,3)
1
>>>
If the script you are trying to run is itself called random.py, then you would have a naming conflict. Choose a different name for your script.
Can you post an example of what you're trying to do? It's not clear from your question what the actual problem is.
Here's an example of how to use the random module:
import random
print random.randint(0,10)
Seems to work fine for me. Check out the methods in the official python documentation for random:
>>> import random
>>> random.random()
0.69130806168332215
>>> random.uniform(1, 10)
8.8384170917436293
>>> random.randint(1, 10)
4
Works for me:
Python 2.5.1 (r251:54863, Jun 15 2008, 18:24:51)
[GCC 4.3.0 20080428 (Red Hat 4.3.0-8)] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> import random
>>> brothers = ['larry', 'curly', 'moe']
>>> random.choice(brothers)
'moe'
>>> random.choice(brothers)
'curly'

Categories