Skip to main content

Questions tagged [python-3.x]

DO NOT USE UNLESS YOUR QUESTION IS FOR PYTHON 3 ONLY. Always use alongside the standard [python] tag.

Filter by
Sorted by
Tagged with
3785 votes
23 answers
5.1m views

Convert bytes to a string in Python 3

I captured the standard output of an external program into a bytes object: >>> from subprocess import * >>> stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0] >>> ...
Tomas Sedovic's user avatar
3026 votes
12 answers
368k views

Why is "1000000000000000 in range(1000000000000001)" so fast in Python 3?

It is my understanding that the range() function, which is actually an object type in Python 3, generates its contents on the fly, similar to a generator. This being the case, I would have expected ...
Rick's user avatar
  • 44.5k
1895 votes
18 answers
1.2m views

Proper way to declare custom exceptions in modern Python?

What's the proper way to declare custom exception classes in modern Python? My primary goal is to follow whatever standard other exception classes have, so that (for instance) any extra string I ...
Nelson's user avatar
  • 29k
1759 votes
33 answers
1.9m views

Relative imports in Python 3

I want to import a function from another file in the same directory. Usually, one of the following works: from .mymodule import myfunction from mymodule import myfunction ...but the other one gives ...
John Smith Optional's user avatar
1642 votes
7 answers
819k views

What is the Python 3 equivalent of "python -m SimpleHTTPServer"

What is the Python 3 equivalent of python -m SimpleHTTPServer?
ryanbraganza's user avatar
  • 17.1k
1491 votes
5 answers
2.8m views

Best way to convert string to bytes in Python 3? [closed]

TypeError: 'str' does not support the buffer interface suggests two possible methods to convert a string to bytes: b = bytes(mystring, 'utf-8') b = mystring.encode('utf-8') Which method is ...
Mark Ransom's user avatar
1314 votes
13 answers
2.0m views

How do I return dictionary keys as a list in Python?

With Python 2.7, I can get dictionary keys, values, or items as a list: >>> newdict = {1:0, 2:0, 3:0} >>> newdict.keys() [1, 2, 3] With Python >= 3.3, I get: >>> newdict....
user avatar
1243 votes
15 answers
888k views

Should I put #! (shebang) in Python scripts, and what form should it take?

Should I put the shebang in my Python scripts? In what form? #!/usr/bin/env python or #!/usr/local/bin/python Are these equally portable? Which form is used most? Note: the tornado project uses ...
treecoder's user avatar
  • 44.4k
1140 votes
43 answers
1.3m views

How can I represent an 'Enum' in Python?

I'm mainly a C# developer, but I'm currently working on a project in Python. How can I represent the equivalent of an Enum in Python?
1105 votes
10 answers
663k views

What is __pycache__?

From what I understand, a cache is an encrypted file of similar files. What do we do with the __pycache__ folder? Is it what we give to people instead of our source code? Is it just my input data? ...
user2063042's user avatar
  • 11.1k
1092 votes
15 answers
1.9m views

UnicodeDecodeError: 'charmap' codec can't decode byte X in position Y: character maps to <undefined>

I'm trying to get a Python 3 program to do some manipulations with a text file filled with information. However, when trying to read the file I get the following error: Traceback (most recent call ...
Eden Crow's user avatar
  • 15.7k
973 votes
11 answers
832k views

What does -> mean in Python function definitions?

I've recently noticed something interesting when looking at Python 3.3 grammar specification: funcdef: 'def' NAME parameters ['->' test] ':' suite The optional 'arrow' block was absent in Python 2 ...
Krotton's user avatar
  • 9,961
962 votes
10 answers
722k views

Fixed digits after decimal with f-strings

Is there an easy way with Python f-strings to fix the number of digits after the decimal point? (Specifically f-strings, not other string formatting options like .format or %) For example, let's say ...
GafferMan2112's user avatar
909 votes
11 answers
2.3m views

"TypeError: a bytes-like object is required, not 'str'" when handling file content in Python 3

I've very recently migrated to Python 3.5. This code was working properly in Python 2.7: with open(fname, 'rb') as f: lines = [x.strip() for x in f.readlines()] for line in lines: tmp = line....
masroore's user avatar
  • 9,996
883 votes
23 answers
1.1m views

Using Python 3 in virtualenv

Using virtualenv, I run my projects with the default version of Python (2.7). On one project, I need to use Python 3.4. I used brew install python3 to install it on my Mac. Now, how do I create a ...
Prometheus's user avatar
  • 33.2k
810 votes
14 answers
556k views

What is the best way to remove accents (normalize) in a Python unicode string?

I have a Unicode string in Python, and I would like to remove all the accents (diacritics). I found on the web an elegant way to do this (in Java): convert the Unicode string to its long normalized ...
MiniQuark's user avatar
  • 47.8k
761 votes
6 answers
316k views

Are dictionaries ordered in Python 3.6+?

Dictionaries are insertion ordered as of Python 3.6. It is described as a CPython implementation detail rather than a language feature. The documentation states: dict() now uses a “compact” ...
Chris_Rands's user avatar
  • 40.4k
699 votes
23 answers
2.0m views

How to install pip with Python 3?

I want to install pip. It should support Python 3, but it requires setuptools, which is available only for Python 2. How can I install pip with Python 3?
deamon's user avatar
  • 91.3k
651 votes
9 answers
1.1m views

How do I use raw_input in Python 3?

In Python 2: raw_input() In Python 3, I get an error: NameError: name 'raw_input' is not defined
Lonnie Price's user avatar
  • 10.4k
647 votes
9 answers
969k views

How do you use StringIO in Python3?

I am using Python 3.2.1 and I can't import the StringIO module. I use io.StringIO and it works, but I can't use it with numpy's genfromtxt() like this: x="1 3\n 4.5 8" numpy....
Babak Abdolahi's user avatar
646 votes
11 answers
638k views

Getting a map() to return a list in Python 3.x [duplicate]

I'm trying to map a list into hex, and then use the list elsewhere. In python 2.6, this was easy: A: Python 2.6: >>> map(chr, [66, 53, 0, 94]) ['B', '5', '\x00', '^'] However, in Python 3....
mozami's user avatar
  • 7,481
624 votes
7 answers
637k views

Error: " 'dict' object has no attribute 'iteritems' "

I'm trying to use NetworkX to read a Shapefile and use the function write_shp() to generate the Shapefiles that will contain the nodes and edges, but when I try to run the code it gives me the ...
friveraa's user avatar
  • 6,355
579 votes
10 answers
1.0m views

Import error: No module name urllib2

Here's my code: import urllib2.request response = urllib2.urlopen("http://www.google.com") html = response.read() print(html) Any help?
user avatar
547 votes
18 answers
1.2m views

List attributes of an object [duplicate]

Is there a way to grab a list of attributes that exist on instances of a class? class new_class(): def __init__(self, number): self.multi = int(number) * 2 self.str = str(number) ...
MadSc13ntist's user avatar
505 votes
20 answers
832k views

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

I would like to include image in a jupyter notebook. If I did the following, it works : from IPython.display import Image Image("img/picture.png") But I would like to include the images in a ...
Ger's user avatar
  • 9,436
501 votes
5 answers
104k views

What does a bare asterisk do in a parameter list? What are "keyword-only" parameters?

What does a bare asterisk in the parameters of a function do? When I looked at the pickle module, I see this: pickle.dump(obj, file, protocol=None, *, fix_imports=True) I know about a single and ...
Eric's user avatar
  • 5,966
495 votes
21 answers
915k views

How to set Python's default version to 3.x on OS X? [duplicate]

I'm running Mountain Lion and the basic default Python version is 2.7. I downloaded Python 3.3 and want to set it as default. Currently: $ python version 2.7.5 $ python3.3 version 3.3 How ...
Marcus's user avatar
  • 9,302
470 votes
14 answers
370k views

Extract a subset of key-value pairs from dictionary?

I have a big dictionary object that has several key value pairs (about 16), but I am only interested in 3 of them. What is the best way (shortest/efficient/most elegant) to subset such dictionary? The ...
Jayesh's user avatar
  • 52.9k
464 votes
3 answers
205k views

Python "raise from" usage

What's the difference between raise and raise from in Python? try: raise ValueError except Exception as e: raise IndexError which yields Traceback (most recent call last): File "tmp.py", ...
darkfeline's user avatar
  • 10.3k
462 votes
11 answers
1.1m views

What does "SyntaxError: Missing parentheses in call to 'print'" mean in Python?

When I try to use a print statement in Python, it gives me this error: >>> print "Hello, World!" File "<stdin>", line 1 print "Hello, World!" ...
ncoghlan's user avatar
  • 41.1k
462 votes
10 answers
576k views

How to correct TypeError: Unicode-objects must be encoded before hashing?

I have this error: Traceback (most recent call last): File "python_md5_cracker.py", line 27, in <module> m.update(line) TypeError: Unicode-objects must be encoded before hashing when I try ...
JohnnyFromBF's user avatar
  • 10.1k
456 votes
9 answers
443k views

Download file from web in Python 3

I am creating a program that will download a .jar (java) file from a web server, by reading the URL that is specified in the .jad file of the same game/application. I'm using Python 3.2.1 I've ...
Bo Milanovich's user avatar
453 votes
12 answers
405k views

What is an alternative to execfile in Python 3?

It seems they canceled in Python 3 all the easy ways to quickly load a script by removing execfile(). Is there an obvious alternative I'm missing?
R S's user avatar
  • 11.7k
441 votes
10 answers
1.6m views

"Unicode Error 'unicodeescape' codec can't decode bytes..." when writing Windows file paths [duplicate]

I am using Python 3.1 on a Windows 7 machine. Russian is the default system language, and utf-8 is the default encoding. Looking at the answer to a previous question, I have attempting using the "...
Eric's user avatar
  • 4,483
441 votes
19 answers
449k views

How to install python3 version of package via pip on Ubuntu?

I have both python2.7 and python3.2 installed in Ubuntu 12.04. The symbolic link python links to python2.7. When I type: sudo pip install package-name It will default install python2 version of ...
kev's user avatar
  • 159k
438 votes
19 answers
1.1m views

Relative imports - ModuleNotFoundError: No module named x

This is the first time I've really sat down and tried python 3, and seem to be failing miserably. I have the following two files: test.py config.py config.py has a few functions defined in it as ...
blitzmann's user avatar
  • 7,645
435 votes
3 answers
673k views

How to convert 'binary string' to normal string in Python3? [duplicate]

For example, I have a string like this(return value of subprocess.check_output): >>> b'a string' b'a string' Whatever I did to it, it is always printed with the annoying b' before the ...
Hanfei Sun's user avatar
  • 46.5k
431 votes
12 answers
799k views

Which is the preferred way to concatenate a string in Python? [duplicate]

Since Python's string can't be changed, I was wondering how to concatenate a string more efficiently? I can write like it: s += stringfromelsewhere or like this: s = [] s.append(somestring) # ...
Max's user avatar
  • 8,005
426 votes
5 answers
206k views

Is __init__.py not required for packages in Python 3.3+

I am using Python 3.5.1. I read the document and the package section here: https://docs.python.org/3/tutorial/modules.html#packages Now, I have the following structure: /home/wujek/Playground/a/b/...
wujek's user avatar
  • 10.7k
409 votes
9 answers
632k views

What is the purpose of "pip install --user ..."?

From pip install --help: --user Install to the Python user install directory for your platform. Typically ~/.local/, or %APPDATA%\Python on Windows. (See the Python documentation for ...
Rob Truxal's user avatar
  • 6,248
400 votes
6 answers
363k views

What's the difference between `raw_input()` and `input()` in Python 3? [duplicate]

What is the difference between raw_input() and input() in Python 3?
pkumar's user avatar
  • 4,771
399 votes
21 answers
677k views

Python 3 ImportError: No module named 'ConfigParser'

I am trying to pip install the MySQL-python package, but I get an ImportError. Jans-MacBook-Pro:~ jan$ /Library/Frameworks/Python.framework/Versions/3.3/bin/pip-3.3 install MySQL-python Downloading/...
if __name__ is None's user avatar
399 votes
9 answers
646k views

What's the correct way to convert bytes to a hex string in Python 3?

What's the correct way to convert bytes to a hex string in Python 3? I see claims of a bytes.hex method, bytes.decode codecs, and have tried other possible functions of least astonishment without ...
Matt Joiner's user avatar
396 votes
6 answers
551k views

NameError: global name 'xrange' is not defined in Python 3

I am getting an error when running a python program: Traceback (most recent call last): File "C:\Program Files (x86)\Wing IDE 101 4.1\src\debug\tserver\_sandbox.py", line 110, in <module> ...
Pip's user avatar
  • 4,437
393 votes
26 answers
1.0m views

Could not find a version that satisfies the requirement tensorflow

I installed the latest version of Python (3.6.4 64-bit) and the latest version of PyCharm (2017.3.3 64-bit). Then I installed some modules in PyCharm (Numpy, Pandas, etc), but when I tried installing ...
Martin W's user avatar
  • 4,778
389 votes
14 answers
1.2m views

How can I print multiple things (fixed text and/or variable values) on the same line, all at once?

I have some code like: score = 100 name = 'Alice' print('Total score for %s is %s', name, score) I want it to print out Total score for Alice is 100, but instead I get Total score for %s is %s Alice ...
user1985351's user avatar
  • 4,649
384 votes
5 answers
1.4m views

Python 3: UnboundLocalError: local variable referenced before assignment [duplicate]

The following code gives the error UnboundLocalError: local variable 'Var1' referenced before assignment: Var1 = 1 Var2 = 0 def function(): if Var2 == 0 and Var1 > 0: print("...
Eden Crow's user avatar
  • 15.7k
381 votes
9 answers
620k views

How to use string.replace() in python 3.x

The string.replace() is deprecated on python 3.x. What is the new way of doing this?
Dewsworld's user avatar
  • 13.9k
380 votes
20 answers
1.5m views

Error UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte

https://github.com/affinelayer/pix2pix-tensorflow/tree/master/tools An error occurred when compiling "process.py" on the above site. python tools/process.py --input_dir data --operation ...
pie's user avatar
  • 4,109
378 votes
11 answers
395k views

How to use a variable inside a regular expression

I'd like to use a variable inside a regex, how can I do this in Python? TEXTO = sys.argv[1] if re.search(r"\b(?=\w)TEXTO\b(?!\w)", subject, re.IGNORECASE): # Successful match else: #...
Pedro Lobito's user avatar
  • 97.5k

1
2 3 4 5
6876