python-2.x

Python how to only accept numbers as a input

…衆ロ難τιáo~ 提交于 2019-11-28 12:26:28
问题 mark= eval(raw_input("What is your mark?")) try: int(mark) except ValueError: try: float(mark) except ValueError: print "This is not a number" So I need to make a python program that looks at your mark and gives you varying responses depending on what it is. However I also need to add a way to stop random text which isn't numbers from being entered into the program. I thought I had found a solution to this but it won't make it it past the first statement to the failsafe code that is meant to

f-strings giving SyntaxError?

你说的曾经没有我的故事 提交于 2019-11-28 12:18:04
I am getting an error message with my Atom reader here, where it is suggesting the first print.(f"message") is delivering an error: File "/Users/permanentmajority/Desktop/Coding/learnpythonbook.py", line 75 print(f"Let's talk about {my_name}.") ^ SyntaxError: invalid syntax [Finished in 0.077s] Code: my_name = 'Zed A. Shaw' my_age = 35 # not a lie my_height = 74 # inches my_weight = 180 #lbs my_eyes = 'Blue' my_teeth = 'White' my_hair = 'Brown' print(f"Let's talk about {my_name}.") print(f"He's {my_height} inches tall.") print(f"He's {my_weight} pounds heavy.") print("Actually that's not too

Why does json.dumps escape non-ascii characters with “\\uxxxx”

眉间皱痕 提交于 2019-11-28 11:42:37
In Python 2, the function json.dumps() will ensure that all non-ascii characters are escaped as \uxxxx . Python 2 Json But isn't this quite confusing because \uxxxx is a unicode character and should be used inside a unicode string. The output of json.dumps() is a str , which is a byte string in Python 2. And thus shouldn't it escape characters as \xhh ? >>> unicode_string = u"\u00f8" >>> print unicode_string ø >>> print json.dumps(unicode_string) "\u00f8" >>> unicode_string.encode("utf8") '\xc3\xb8' That's exactly the point. You get a byte string back, not a Unicode string. Thus the Unicode

Many threads to write log file at same time in Python

本小妞迷上赌 提交于 2019-11-28 11:16:16
I am writing a script to retrieve WMI info from many computers at the same time then write this info in a text file: f = open("results.txt", 'w+') ## to clean the results file before the start def filesize(asset): f = open("results.txt", 'a+') c = wmi.WMI(asset) wql = 'SELECT FileSize,Name FROM CIM_DataFile where (Drive="D:" OR Drive="E:") and Caption like "%file%"' for item in c.query(wql): print >> f, item.Name.split("\\")[2].strip().upper(), str(item.FileSize) class myThread (threading.Thread): def __init__(self,name): threading.Thread.__init__(self) self.name = name def run(self):

Python list() vs list comprehension building speed

£可爱£侵袭症+ 提交于 2019-11-28 10:50:54
This is interesting; list() to force an iterator to get the actual list is so much faster than [x for x in someList] (comprehension). Is this for real or is my test just too simple? Below is the code: import time timer = time.clock() for i in xrange(90): #localList = [x for x in xrange(1000000)] #Very slow, took me 6.8s localList = list(xrange(1000000)) #Very fast, took me 0.9s print localList[999999] #make sure list is really evaluated. print "Total time: ", time.clock() - timer The list comprehension executes the loop in Python bytecode, just like a regular for loop. The list() call iterates

How can I convert Unicode to uppercase to print it?

混江龙づ霸主 提交于 2019-11-28 10:40:02
I have this: >>> print 'example' example >>> print 'exámple' exámple >>> print 'exámple'.upper() EXáMPLE What I need to do to print: EXÁMPLE (Where the 'a' gets its accute accent, but in uppercase.) I'm using Python 2.6. I think it's as simple as not converting to ASCII first. >>> print u'exámple'.upper() EXÁMPLE In python 2.x, just convert the string to unicode before calling upper(). Using your code, which is in utf-8 format on this webpage: >>> s = 'exámple' >>> s 'ex\xc3\xa1mple' # my terminal is not utf8. c3a1 is the UTF-8 hex for á >>> s.decode('utf-8').upper() u'EX\xc1MPLE' # c1 is the

Why does this argparse code behave differently between Python 2 and 3?

跟風遠走 提交于 2019-11-28 10:01:12
The following code, using argparse's subparsers, fails on Python 3 but runs as expected in Python 2. After comparing the docs, I still can't tell why. #!/usr/bin/env python from __future__ import print_function from argparse import ArgumentParser def action(args): print(args) if __name__ == '__main__': std = ArgumentParser(add_help=False) std.add_argument('standard') ap = ArgumentParser() sp = ap.add_subparsers() cmd = sp.add_parser('subcommand', parents=[std], description='Do subcommand') cmd.add_argument('arg') cmd.set_defaults(do=action) args = ap.parse_args() args.do(args) The output from

How do I convert a unicode to a string at the Python level?

心已入冬 提交于 2019-11-28 09:54:42
The following unicode and string can exist on their own if defined explicitly: >>> value_str='Andr\xc3\xa9' >>> value_uni=u'Andr\xc3\xa9' If I only have u'Andr\xc3\xa9' assigned to a variable like above, how do I convert it to 'Andr\xc3\xa9' in Python 2.5 or 2.6? EDIT: I did the following: >>> value_uni.encode('latin-1') 'Andr\xc3\xa9' which fixes my issue. Can someone explain to me what exactly is happening? You seem to have gotten your encodings muddled up. It seems likely that what you really want is u'Andr\xe9' which is equivalent to 'André' . But what you have seems to be a UTF-8 encoding

feature: **kwargs allowing improperly named variables

混江龙づ霸主 提交于 2019-11-28 08:41:40
问题 The following is invalid python: def myInvalidFun(kw arg zero=6): pass The following is valid python: def myValidFun(**kwargs): if kwargs.has_key("kw arg zero"): pass To call myValidFun , however, is tricky. For instance, the next few approaches do not work: myValidFun(kw arg zero=6) # SyntaxError: invalid syntax myValidFun("kw arg zero"=6) # SyntaxError: keyword can't be an expression kwargs = dict("kw arg zero"=6) # SyntaxError: keyword can't be an expression myValidFun(**kwargs) (Perhaps