Re: [Tutor] Distributing Python Code for Commercial Porpoises?
On Sun, Aug 8, 2010 at 7:57 PM, Steven D'Aprano wrote: > On Mon, 9 Aug 2010 04:44:37 am David Hutto wrote: > >> Four words... Software is python's propaganda. > > Four more words: please trim unnecessary quoting. No problem buddy pal. > > > -- > Steven D'Aprano > ___ > Tutor maillist - tu...@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor > ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need a mentor
On Mon, Aug 9, 2010 at 12:23 PM, Steven D'Aprano wrote: > On Mon, 9 Aug 2010 12:16:11 pm Ranjith Kumar wrote: > > Hi all, > > I`m doing a python based project, I need a mentor who can guide > > me and help me to complete the project. > Sorry Mr. Steven I think u caught it wrong I`m not asking to trainee me I almost completed this script Are you offering to pay for professional help for a commercial project, > First thing is this is not a commercial Project, I`m just trying to take my writing of python scripts to next level. > looking for volunteers to work on an open-source project with you, After I complete this project I will send the code so any volunteers can optimize the code so that we can provide better solution for open source world and I will definitely upload this project under GPL Licence in code.google.com and sourceforgue.net. > or just looking for a kind and generous soul who is happy to donate many, > many hours of work teaching you application development in Python? > I think here comes the little bit misunderstanding I don`t want to waste your several hours the thing I post is just a core of my project a small part like. These are the four things, I need to know is this 1) Configuring window should runs automatically only first time if the user wants to reconfigure the file again they should run configuring module separately. 2) This script is to start it automatically on every login and stay running on background until i shut download the machine. 3) I need a best alternative way for switch case statement 4) Lastly I need to know is how to print the list of web browsers installed on a machine. Thats it, Thank you and sorry for trouble I gave you Mr.Steven -- Cheers Ranjith, http://ranjith10z.wordpress.com http://ranjithtenz.wordpress.com ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.urandom()
Richard D. Moores wrote: On Sun, Aug 8, 2010 at 08:11, bob gailer wrote: On 8/8/2010 1:57 AM, Richard D. Moores wrote: How were we supposed to know that all the hexes have 2 digits? In version 2.6.5 Language Reference 2.4.1 - String literals: \xhh Character with hex value hh But os.urandom(6) b'\x13\xf1\x138a\xcc' In my Active Python 3.1 docs, Language Ref 2.4.1. String and Bytes literals, I have The same as what you quoted, plus a couple of footnotes: \xhh Character with hex value hh (2,3) That footnote 2, "Unlike in Standard C, at most two hex digits are accepted.", seems necessary; otherwise that \x138a could be seen by my former, byte-ignorant self as a \x, and puzzled about why I got only 4 bytes, not 6. :) But I never would have thought to have looked in the docs where you did. Dick Big difference between 2.x and 3.x. In 3.x, strings are Unicode, and may be stored either in 16bit or 32bit form (Windows usually compiled using the former, and Linux the latter). Presumably in 3.x, urandom returns a byte string (see the b'' form), which is 8 bits each, same as 2.x strings. So you'd expect only two hex digits for each character. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need a mentor
On Mon, 9 Aug 2010 07:21:03 pm Ranjith Kumar wrote: > On Mon, Aug 9, 2010 at 12:23 PM, Steven D'Aprano wrote: > > On Mon, 9 Aug 2010 12:16:11 pm Ranjith Kumar wrote: > > > Hi all, > > > I`m doing a python based project, I need a mentor who can > > > guide me and help me to complete the project. > > Sorry Mr. Steven I think u caught it wrong I`m not asking to trainee > me I almost completed this script It's not clear exactly what you want. Lists like this work best when you ask *specific* questions like "how do I set a cookies from Python?" or "what's the difference between a list and a tuple?", not vague requests for a mentor. After reading both your posts, I'm still not entirely sure I understand what you want, but I'll try... [...] > After I complete this project I will send the code so any volunteers > can optimize the code so that we can provide better solution for open > source world and I will definitely upload this project under GPL > Licence in code.google.com and sourceforgue.net. It's not compulsory :) I don't understand why you think you need to optimize the code. Is it too slow? [...] > These are the four things, I need to know is this > 1) Configuring window should runs automatically only first > time if the user wants to reconfigure the file again they should run > configuring module separately. That's a statement, not a question. What do you want to know? "Is this a good idea?" Depends on the application. Most applications give the user a Preferences or Settings menu so they can reconfigure the app at any time. But since I don't really know what your application does, I'm not sure if this is appropriate. "How do I do it?" The usual way is to have the application look for a configuration file in some place. If it is missing, then create a new one. If it is present, then read the file and use it as the config. > 2) This script is to start it automatically on every login and stay > running on background until i shut download the machine. Again, that's not a question, it's a statement. What do you want to know? "Is this a good idea?" Who knows? What does your program do? "How do I do it?" That depends. What operating system is your application supposed to run under? > 3) I need a best alternative way for switch case statement There is no "best alternative", it depends on the nature of the case statement you are replacing. If it is only a few cases, or if each test is a different sort of test: # pseudo-code case: x == 1: spam(arg) x > 2: ham(arg) y/x < 0: cheese(arg) otherwise: pickles(arg) the best alternative is a series of if...elif tests. If you have a series of simple equality comparisons, and you can write the case clause as a single function call: # pseudo-code case of x: 1: spam(arg) 2: ham(arg) 3: cheese(arg) otherwise: pickles(arg) it is probably better re-writing it as a dispatch table: # python table = {1: spam, 2: ham, 3: cheese} func = table.get(x, pickles) func(arg) There are probably other alternatives that will be better depending on exactly what you are trying to do. > 4) Lastly I need to know is how to print the list of web browsers > installed on a machine. Printing it is easy: you print it the same way you print anything else: call print to output to the terminal, or generate a print job to send to a physical printer. The hard part is finding out what web browsers are installed on a machine. That's a hard problem, because there's no canonical list of "web browsers" for a computer. Take my machine, for example. I have: firefox 2.x firefox 3.x epiphany galeon konquorer links lynx and they're just the ones I know of. The problems are: * It is hard to tell what is a web browser and what isn't. If Adobe Acrobat lets you embed clickable links to http:// URLs in PDF files, does that make Acrobat a web browser? I suppose it does, but some people will say not. If Outlook displays web pages, is it a web browser? You can click on a link in a Word document, and Word will open that web page for you -- is it a browser? * Even if you decide exactly what is a web browser, there's no list of them anywhere. To find out which they are, you would need to start with a list of all the applications on the computer (what's an application? what if there are thousands of them?), and then somehow inspect each one and try to recognise whether or not it is a web browser or not. How? You probably can get the name of the *registered* web browser, but the way you do that will depend on the operating system and desktop environment. E.g. under Windows there is probably a registry setting that specifies which application to use as the default web browser. Or you can keep a list of possibilities, and search for them, ignoring anything else. Or you can ask the user. Or you can look at Python's webbrowser module and see what it does. So the answer will depend on why you want
Re: [Tutor] Reading every 5th line
nitin chandra wrote: This may help you get started. FileNames ="FileName01", "FileName02", ..., "FileName24"] for File in FileNames: List =pen(File, 'r').readlines() for Start in [[14, "%s-1" % File], [15,"%s-2" % File]]: OutList =] for Line in range(Start[0]-1, 3024, 5): OutList.append(List[Line]) open(("%s.txt" % Start[1]), 'w').writelines(OutList) P.S. My code writing style isn't very conventional. Note that three of those lines may be replaced with a slice (untested) OutList =] for Line in range(Start[0]-1, 3024, 5): OutList.append(List[Line]) OutList = List[Start[0]-1: 3024: 5] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Need a mentor
On Mon, Aug 9, 2010 at 3:28 PM, Steven D'Aprano wrote: > On Mon, 9 Aug 2010 07:21:03 pm Ranjith Kumar wrote: > > On Mon, Aug 9, 2010 at 12:23 PM, Steven D'Aprano > wrote: > > > On Mon, 9 Aug 2010 12:16:11 pm Ranjith Kumar wrote: > > > > Hi all, > > > > I`m doing a python based project, I need a mentor who can > > > > guide me and help me to complete the project. > > > > Sorry Mr. Steven I think u caught it wrong I`m not asking to trainee > > me I almost completed this script > You need a mentor to help you :-/ . What is the problem is you work upon your script and ask doubts here? You are confusing university projects with real-life projects I think. In universities you choose a mentor and he help you out. Here you work on your project, ask doubts and community help you out. Isn't it good to have whole of the community helping you rather than one single person. > > It's not clear exactly what you want. Lists like this work best when you > ask *specific* questions like "how do I set a cookies from Python?" > or "what's the difference between a list and a tuple?", not vague > requests for a mentor. > > After reading both your posts, I'm still not entirely sure I understand > what you want, but I'll try... > > [...] > > After I complete this project I will send the code so any volunteers > > can optimize the code so that we can provide better solution for open > > source world and I will definitely upload this project under GPL > > Licence in code.google.com and sourceforgue.net. > > It's not compulsory :) > > I don't understand why you think you need to optimize the code. Is it > too slow? > I think he means that after his project is over, he will open-source the code so that other's may improve upon it. > > > > [...] > > These are the four things, I need to know is this > > 1) Configuring window should runs automatically only first > > time if the user wants to reconfigure the file again they should run > > configuring module separately. > > That's a statement, not a question. What do you want to know? > > "Is this a good idea?" > > Depends on the application. Most applications give the user a > Preferences or Settings menu so they can reconfigure the app at any > time. But since I don't really know what your application does, I'm not > sure if this is appropriate. > > "How do I do it?" > > The usual way is to have the application look for a configuration file > in some place. If it is missing, then create a new one. If it is > present, then read the file and use it as the config. > > > > 2) This script is to start it automatically on every login and stay > > running on background until i shut download the machine. > > Again, that's not a question, it's a statement. What do you want to > know? > > "Is this a good idea?" > > Who knows? What does your program do? > > "How do I do it?" > > That depends. What operating system is your application supposed to run > under? > > > > > > 3) I need a best alternative way for switch case statement > > There is no "best alternative", it depends on the nature of the case > statement you are replacing. > > If it is only a few cases, or if each test is a different sort of test: > > # pseudo-code > case: > x == 1: >spam(arg) > x > 2: >ham(arg) > y/x < 0: >cheese(arg) > otherwise: >pickles(arg) > > > the best alternative is a series of if...elif tests. > > If you have a series of simple equality comparisons, and you can write > the case clause as a single function call: > > > # pseudo-code > case of x: > 1: >spam(arg) > 2: >ham(arg) > 3: >cheese(arg) > otherwise: >pickles(arg) > > > it is probably better re-writing it as a dispatch table: > > # python > table = {1: spam, 2: ham, 3: cheese} > func = table.get(x, pickles) > func(arg) > > > There are probably other alternatives that will be better depending on > exactly what you are trying to do. > > > > > 4) Lastly I need to know is how to print the list of web browsers > > installed on a machine. > > Printing it is easy: you print it the same way you print anything else: > call print to output to the terminal, or generate a print job to send > to a physical printer. > > The hard part is finding out what web browsers are installed on a > machine. That's a hard problem, because there's no canonical list > of "web browsers" for a computer. > > Take my machine, for example. I have: > > firefox 2.x > firefox 3.x > epiphany > galeon > konquorer > links > lynx > > and they're just the ones I know of. The problems are: > > * It is hard to tell what is a web browser and what isn't. If Adobe > Acrobat lets you embed clickable links to http:// URLs in PDF files, > does that make Acrobat a web browser? I suppose it does, but some > people will say not. If Outlook displays web pages, is it a web > browser? You can click on a link in a Word document, and Word will open > that web page for you -- is it a browser? > > * Even if you decide exactly what is a web browser, there's no list of >
Re: [Tutor] os.urandom()
On Mon, 9 Aug 2010 07:23:56 pm Dave Angel wrote: > Big difference between 2.x and 3.x. In 3.x, strings are Unicode, and > may be stored either in 16bit or 32bit form (Windows usually compiled > using the former, and Linux the latter). That's an internal storage that you (generic you) the Python programmer doesn't see, except perhaps indirectly via memory consumption. Do you know how many bits are used to store floats? If you try: >>> sys.getsizeof(1.1) 16 in Python 2.6 or better, it tells you that a float *object* takes 16 bytes, but it doesn't tell you anything about the underlying C-level floating point data. And a float that prints like: 1.0 takes up exactly the same storage as one that prints like: 1.234567890123456789 We can do a bit better with unicode strings: >>> sys.getsizeof(u'a') - sys.getsizeof(u'') 2 but frankly, who cares? It doesn't *mean* anything. Whether a character takes up two bytes, or twenty-two bytes, is irrelevant to how it prints. > Presumably in 3.x, urandom returns a byte string (see the b'' > form), which is 8 bits each, same as 2.x strings. So you'd expect > only two hex digits for each character. It looks like you've missed the point that bytes don't always display as two hex digits. Using Python 3.1, we can see some bytes display in hex-escape form, e.g.: >>> bytes([0, 1, 20, 30, 200]) b'\x00\x01\x14\x1e\xc8' some will display in character-escape form: >>> bytes([9, 10, 13]) b'\t\n\r' and some will display as unescaped ASCII characters: >>> bytes([40, 41, 80, 90, 110]) b'()PZn' So you can't make any definitive statement that the output of urandom will be displayed in hex form. Because the output is random, you might, by some incredible fluke, get: >>> os.urandom(6) b'hello ' >>> os.urandom(6) b'world!' I wouldn't like to bet on it though. By my calculation, the odds of that exact output is 1 in 79228162514264337593543950336. The odds of getting nothing but hex-escaped characters is a bit better. By my estimate, the odds of getting 12 hex-escaped characters in a row is about 1 in 330. For six in a row, it's about 1 in 18 or so. By the way, an interesting aside... bytes aren't always 8 bits. Of course, on just about all machines that have Python on them, they will be, but there are still machines and devices such as signal processors where bytes are something other than 8 bits. Historically, common values included 5, 6, 7, 9, or 16 bits, and the C and C++ standards still define a constant CHAR_BIT to specify the number of bits in a byte. -- Steven D'Aprano ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.urandom()
Steven D'Aprano wrote: On Mon, 9 Aug 2010 07:23:56 pm Dave Angel wrote: Big difference between 2.x and 3.x. In 3.x, strings are Unicode, and may be stored either in 16bit or 32bit form (Windows usually compiled using the former, and Linux the latter). That's an internal storage that you (generic you) the Python programmer doesn't see, except perhaps indirectly via memory consumption. Do you know how many bits are used to store floats? If you try: You've missed including the context that I was responding to. I'm well aware of many historical architectures, and have dealt with the differences between the coding on an IBM 26 keypunch and an IBM 29. As well as converting the 12 bit raw bits coming from a hollerith card into various forms compatible with the six characters per word storage of the CDC 6400. I doubt however that Python could be ported to a machine with a 9 bit byte or a 7 bit byte, and remain fully compatible. The OP was talking about the display of \xhh and thought he had discovered a discrepancy between the docs on 2.x and 3.x. And for that purpose it is quite likely relevant that 3.x has characters that won't fit in 8 bits, and thus be describable in two hex digits. I was trying to point out that characters in 3.x are more than 16 bits, and thus would require more than two hex digits. But a b'' string does not. I don't usually use 3.1, but I was curious to discover that repr() won't display a string with an arbitrary Unicode character in it. ++a = chr(300) ++repr(a) File "c:\progfiles\python31\lib\encodings\cp437.py", line 19, in encode return codecs.charmap_encode(input,self.errors,encoding_map)[0] UnicodeEncodeError: 'charmap' codec can't encode character '\u012c' in position 2: character maps to I would have expected it to use something like: "x\012c" I realize that it can't produce a pair of bytes without a (non-ASCII) decoding, but it doesn't make sense to me that repr() doesn't display something reasonable, like hex. FWIW, my sys.stdout.encoding is cp437. DaveA ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: Need mentor
On Mon, Aug 9, 2010 at 1:32 AM, Ranjith Kumar wrote: > Hi all, > > I have described the theme of my project here, > Cheers > Ranjith, > This sounds kind of like homework. Is it homework? If not, where did you get this spec from? Thanks, -Luke ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Question about strings
Hi, I'm trying to solve an exercise, a beginners one but I have a question. So the exercise sounds like this: Define a string s = ’colorless’. Write a Python statement that changes this to ’colour- less’, using only the slice and concatenation operations. So I did wrote this: *1)s = 'colorless' 2)ss = s[:4] + 'u' + s[4:] 3)print(ss) *I do not understand something. So on the second line, the slicing lasts from the start of the s string to the forth character. But from were does the counting start? 0 or 1? From this code it's obvious that it starts from one, but how, strings counting doesn't start from 0? If I do len(s) i get 9 but if I do s[9] I get an error, out of range. Can please someone clear me this indexing thing? It's so frustrating and confusing. * * ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about strings
Hey email in plain text in the future, HTML is not kind to mobile screens and in general you should plaintext reply to tech lists. All list indices start from 0. But you don't get the last value. So slice[1:5] would skip the first char and then include the next 3. It's the same as range. Range(1,100) returns 1,2,,99. Hope that helps -luke Sent from my iPhone On Aug 9, 2010, at 11:02 AM, Daniel <.aste...@gmail.com> wrote: > Hi, I'm trying to solve an exercise, a beginners one but I have a question. > So the exercise sounds like this: > > Define a string s = ’colorless’. Write a Python statement that changes this > to ’colour- > less’, using only the slice and concatenation operations. > > So I did wrote this: > 1)s = 'colorless' > 2)ss = s[:4] + 'u' + s[4:] > > 3)print(ss) > > I do not understand something. So on the second line, the slicing lasts from > the start of the s string to the forth character. But from were > > does the counting start? 0 or 1? From this code it's obvious that it starts > from one, but how, strings counting doesn't start from 0? If I do > len(s) i get 9 but if I do s[9] I get an error, out of range. Can please > someone clear me this indexing thing? It's so frustrating and > > confusing. > > ___ > Tutor maillist - Tutor@python.org > To unsubscribe or change subscription options: > http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Question about strings
"Daniel" wrote *1)s = 'colorless' 2)ss = s[:4] + 'u' + s[4:] *I do not understand something. So on the second line, the slicing lasts from the start of the s string to the forth character. Correct, slices include the first index but not the last. does the counting start? 0 or 1? It starts with 0. [:4] means 0,1,2,3 From this code it's obvious that it starts from one, but how, strings counting doesn't start from 0? No, it starts from 0. len(s) i get 9 but if I do s[9] I get an error, out of range. Yes but if you do range(0,len(s)) you get the right set of values to index s. - 0...(9-1) A slice works like range() please someone clear me this indexing thing? It's so frustrating and confusing. It is confusing until you get used to it. You will find over time that it is actually more convenient that way, but it is very strange for newbies. There are some languages that start indexing at 1 but they get into all sorts of complications in other areas, most language designers have settled for zero based indexes as the best overall solution. HTH, -- Alan Gauld Author of the Learn to Program web site http://www.alan-g.me.uk/ ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] Weekly Python Tips mailing list is ready to join
I asked a few days ago if there'd be interest in a Python Tips list that sends out Python tips to your inbox each week - I've had a lovely response over the weekend so I'll proceed with creating the list. Thanks for the replies! As I mentioned I have a whole set of tips planned. They'll cover useful stuff (like "how to write Pythonically"), cool stuff (including some 3D, gaming, web-dev and maths), links to modules you probably haven't heard of yet and guest tips from known Pythonistas. I'll be sending out one tip per week, it'll include some source code and links to useful resources. There will definitely be links back to useful ShowMeDo videos to illustrate the ideas. I'll publish the first set of tips when I have 50 people on the list - this way I'll get good feedback on what's required which will guide which tips I cover next. To join the list send an email here: weeklypyt...@aweber.com and accept the opt-in message you receive. It is an Aweber mailing list (they're a well known mailing list host) and you can unsubscribe at any time if it isn't helpful. I promise no spam or foolishness (and I certainly won't pass on your email address to 3rd parties), you'll just get helpful Python tips. It'll be quiet for a week or two whilst I gather the first 50 sign-ups and then I'll start posting out the tips. Looking forward to building the list and getting some feedback, Ian. -- Ian Ozsvald (A.I. researcher, screencaster) i...@ianozsvald.com http://IanOzsvald.com http://ShowMeDo.com http://MorConsulting.com/ http://blog.AICookbook.com/ http://TheScreencastingHandbook.com http://FivePoundApp.com/ http://twitter.com/IanOzsvald ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] Fwd: Need mentor
Exactly what do you want your mentor to do? -- Bob Gailer 919-636-4239 Chapel Hill NC ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.urandom()
On Mon, 9 Aug 2010 11:51:34 pm you wrote: > Steven D'Aprano wrote: > > On Mon, 9 Aug 2010 07:23:56 pm Dave Angel wrote: > >> Big difference between 2.x and 3.x. In 3.x, strings are Unicode, > >> and may be stored either in 16bit or 32bit form (Windows usually > >> compiled using the former, and Linux the latter). > > > > That's an internal storage that you (generic you) the Python > > programmer doesn't see, except perhaps indirectly via memory > > consumption. > > > > Do you know how many bits are used to store floats? If you try: > > > > You've missed including the context that I was responding to. Possibly so, but I didn't miss *reading* the context, and it wasn't clear to me exactly what you were trying to get across to Richard. Maybe that was just my poor reading comprehension, or maybe the two of you had gone of on a tangent that was confusing. At least to me. > I'm > well aware of many historical architectures, and have dealt with the > differences between the coding on an IBM 26 keypunch and an IBM 29. I only know of these ancient machines second or third hand. In any case, my mention of non-8-bit bytes was clearly marked as an aside, and not meant to imply that the number of bits in a byte will vary from one Python implementation to another. The point of my post was that the internal storage of Unicode strings is virtually irrelevant to the Python programmer. Strings are strings, and the way Python stores them in memory is as irrelevant as the way it stores tuples, or floats, or long ints, or None. That is to say, the way they are stored will effect speed and memory consumption, but as a Python programmer, we have very little say in the matter. We deal with high-level objects. Unless we hack the Python compiler, or possibly do strange and dangerous things with ctypes, we don't have any access to the internal format of those objects. [...] > The OP was talking about the display of \xhh and thought he had > discovered a discrepancy between the docs on 2.x and 3.x. And for > that purpose it is quite likely relevant that 3.x has characters that > won't fit in 8 bits, and thus be describable in two hex digits. I > was trying to point out that characters in 3.x are more than 16 bits, > and thus would require more than two hex digits. The number of bytes used for the in-memory unicode implementations does *not* relate to the number of bytes used when decoded to bytes. They're independent. Unicode strings are sequences of code points, integers between 0 and 10 in base-16, or 0 and 1114111 in base 10. The in-memory storage of those code points is an implementation detail. The two most common implementations are the 2-byte and 4-byte version, but even there it will depend on whether your platform is big-endian or little-endian or something else. Take code point 61 (base-16), or the character 'a'. Does it matter whether that is stored in memory as a two-byte chunk 0061 or 6100, or a four-byte chunk 0061, 6100, 0061 or 6100, or something else? No. When you print the character 'a', it prints as character 'a' regardless of what the internal storage looks like. Characters are characters, and the internal storage doesn't matter. We could, if we wanted, write an implementation of Unicode in Python, where the code points are 16 byte (128 bit) int objects. It would be horribly slow, but it would still be Unicode, and the character 'a' would be represented in memory by whatever the PyIntObject C data structure happens to be. (Whatever it is, it won't be pretty.) To get bytes, the internal storage of Unicode doesn't matter. You need to specify an encoding, and the result you get depends on that encoding, not the internal storage in memory: >>> s = 'a' + chr(220) >>> print(s) aÜ >>> s.encode('latin-1') b'a\xdc' >>> s.encode('utf-8') b'a\xc3\x9c' >>> s.encode('utf-16') b'\xff\xfea\x00\xdc\x00' > But a b'' string does not. Naturally. By definition, each byte in a sequence of bytes is a single byte. > I don't usually use 3.1, but I was curious to discover that repr() > won't display a string with an arbitrary Unicode character in it. repr() doesn't display anything. repr() returns the string representation, not the byte representation. Try this: a = chr(300) b = repr(a) My prediction is that it will succeed, and not fail. Then try this: print(a) My prediction is that it will fail with UnicodeEncodeError. It is is your terminal that can't display arbitrary Unicode characters, because your terminal have a weird encoding set. Fix the terminal, and you won't have the problem: >>> a = chr(300) >>> print(a, repr(a)) Ĭ 'Ĭ' >>> sys.stdout.encoding 'UTF-8' There's almost never any good reason for using an encoding other than utf-8. > I realize that it can't produce a pair of bytes without a (non-ASCII) > decoding, No, you have that backwards. Strings encode to bytes. Bytes decode to strings. > but it doesn't make sense to me that repr
Re: [Tutor] Questions regarding strings
On Sun, Aug 8, 2010 at 1:04 PM, Daniel wrote: > > Can someone please explain this to me? Thank you so much and I wish everyone > a great day! Beyond what Hugo mentioned in his message, take a look at the tutorial: http://docs.python.org/tutorial/introduction.html#strings I don't see a way to directly link to the section about subscripting and slicing strings, but it's a bit below that link, and starts with "Strings can be subscripted (indexed); like in C, the first character of a string has subscript (index) 0" -- Jerry ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] problem loading and array from an external file
Hi, my name is Bill and I am completely stuck. I have a little bit of code I am working with for the sole purpose of coding in order to learn Python. In order to learn a programming language, I very often use a little text based map of rooms traversal game. So far, so good. However, this time I decided to learn some file operations so I am trying to read the data in from an external file rather than preloading an array inside the code itself. I am able to open the file and read from it. However, I am getting unexpected results when filling the array. Instead of each row in the array being loaded with the matching line in the data file, by the end of the loops all the rows in the array end up being filled with the last line of the data file. I have stepped and traced through it and cannot figure out where I am going wrong. This may not be a Python issue at all, but is likely me being way off in the weeds on my algorithm. This is only the portion of the code for loading the array from the file. I am writing this in Python 3. I believe my problem is somewhere in the read_maze_data_file() function. There are lots of unnecessary extra print statements in this code because I was trying to carefully follow the state of the variables as the code ran. If anyone can point out where I am going wrong, I would really appreciate it. The code: # N S E W U D room0 = [0,0,0,0,0,0,0] room1 = [0,0,0,0,0,0,0] #Pad the first place so that rooms may room2 = [0,0,0,0,0,0,0] #be referenced naturally room3 = [0,0,0,0,0,0,0] room4 = [0,0,0,0,0,0,0] #First places will have special purposes room5 = [0,0,0,0,0,0,0] room6 = [0,0,0,0,0,0,0] #initialize the array with zeros room7 = [0,0,0,0,0,0,0] room = [room0,room1,room2,room3,room4,room5,room6,room7] def clearscreen(numlines=100): """Clear the console. numlines is an optional argument used only as a fall-back. """ import os if os.name == "posix": # Unix/Linux/MacOS/BSD/etc os.system('clear') elif os.name in ("nt", "dos", "ce"): # DOS/Windows os.system('CLS') else: # Fallback for other operating systems. print('\n' * numlines) print(os.name) def print_map(): print("+-+") print('|','MAP: ','N','S','E','W','U','D','|', sep="", end="") for x in range(1,8): print() print("|","room",x,"> ", sep="", end="") for y in range(1,7): print(room[x][y], end="") print("|", end="") print() print("+-+", end="") def read_maze_data_file(): roomx = [0,0,0,0,0,0,0] n, m = 0, 0 try: filename = 'mazegame.dat' textf = open(filename, 'r') except IOError: print ('Cannot open file %s for reading' % filename) import sys sys.exit(0) # reads one line at a time for line in textf: print("raw line in file: ",line, end="") tempwords = line.split(None) print ("line as read from file: ",tempwords) for n in range(0, len(room)-1): roomx[n] = tempwords[n] #print(roomx[n]) print("roomx",roomx) room[m] = roomx print("room ",m,room[m]) print("current state of room array") print("room 0",room[0]) print("room 1",room[1]) print("room 2",room[2]) print("room 3",room[3]) print("room 4",room[4]) print("room 5",room[5]) print("room 6",room[6]) print("room 7",room[7]) m += 1 textf.close() return(room) #END read_maze_data_file() #-MAIN SECTION- clearscreen() print("LOAD AN ARRARY FROM A FILE") print(" by Bill Allen") print() print("initial state of room array") print(room) print() print("data from file") room_final = read_maze_data_file() print("from MAIN") print(room_final) print() print("a PRINT_MAP call from MAIN") print_map() print() print() === partial sample output showing the current incorrect results: a PRINT_MAP call from MAIN +-+ |MAP: NSEWUD| |room1> 50| |room2> 50| |room3> 50| |room4> 50| |room5> 50| |room6> 50| |room7> 50| +-+ = the contents of the data file, mazegame.dat 0 0 0 0 0 0 0 0 0 4 2 0 0 0 0 0 0 1 3 6 0 0 0 5 0 2 0 0 0 1 0 5 0 0 0 0 3 0 0 4 0 7 0 0 0 0 0 0 2 0 0 0 0 0 5 0 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] problem loading and array from an external file
On 8/9/2010 10:55 PM, Bill Allen wrote: Hi, my name is Bill and I am completely stuck. I have a little bit of code I am working with for the sole purpose of coding in order to learn Python. In order to learn a programming language, I very often use a little text based map of rooms traversal game. So far, so good. However, this time I decided to learn some file operations so I am trying to read the data in from an external file rather than preloading an array inside the code itself. I am able to open the file and read from it. However, I am getting unexpected results when filling the array. Instead of each row in the array being loaded with the matching line in the data file, by the end of the loops all the rows in the array end up being filled with the last line of the data file. I have stepped and traced through it and cannot figure out where I am going wrong. How did you step thru it? If you do it very precisely the problem will be evident. I'd prefer you discover it by careful step-thru rather than feeding you the answer. This may not be a Python issue at all, but is likely me being way off in the weeds on my algorithm. This is only the portion of the code for loading the array from the file. I am writing this in Python 3. I believe my problem is somewhere in the read_maze_data_file() function. That is accurate. There are lots of unnecessary extra print statements in this code because I was trying to carefully follow the state of the variables as the code ran. If anyone can point out where I am going wrong, I would really appreciate it. As mentioned above you have a bug in your step-throuogh process. Write down the variables that are affected by each statement and note their new values. The code: # N S E W U D room0 = [0,0,0,0,0,0,0] room1 = [0,0,0,0,0,0,0] #Pad the first place so that rooms may room2 = [0,0,0,0,0,0,0] #be referenced naturally room3 = [0,0,0,0,0,0,0] room4 = [0,0,0,0,0,0,0] #First places will have special purposes room5 = [0,0,0,0,0,0,0] room6 = [0,0,0,0,0,0,0] #initialize the array with zeros room7 = [0,0,0,0,0,0,0] room = [room0,room1,room2,room3,room4,room5,room6,room7] def clearscreen(numlines=100): """Clear the console. numlines is an optional argument used only as a fall-back. """ import os if os.name == "posix": # Unix/Linux/MacOS/BSD/etc os.system('clear') elif os.name in ("nt", "dos", "ce"): # DOS/Windows os.system('CLS') else: # Fallback for other operating systems. print('\n' * numlines) print(os.name) def print_map(): print("+-+") print('|','MAP: ','N','S','E','W','U','D','|', sep="", end="") for x in range(1,8): print() print("|","room",x,"> ", sep="", end="") for y in range(1,7): print(room[x][y], end="") print("|", end="") print() print("+-+", end="") def read_maze_data_file(): roomx = [0,0,0,0,0,0,0] n, m = 0, 0 try: filename = 'mazegame.dat' textf = open(filename, 'r') except IOError: print ('Cannot open file %s for reading' % filename) import sys sys.exit(0) # reads one line at a time for line in textf: print("raw line in file: ",line, end="") tempwords = line.split(None) print ("line as read from file: ",tempwords) for n in range(0, len(room)-1): roomx[n] = tempwords[n] #print(roomx[n]) print("roomx",roomx) room[m] = roomx print("room ",m,room[m]) print("current state of room array") print("room 0",room[0]) print("room 1",room[1]) print("room 2",room[2]) print("room 3",room[3]) print("room 4",room[4]) print("room 5",room[5]) print("room 6",room[6]) print("room 7",room[7]) m += 1 textf.close() return(room) #END read_maze_data_file() #-MAIN SECTION- clearscreen() print("LOAD AN ARRARY FROM A FILE") print(" by Bill Allen") print() print("initial state of room array") print(room) print() print("data from file") room_final = read_maze_data_file() print("from MAIN") print(room_final) print() print("a PRINT_MAP call from MAIN") print_map() print() print() === partial sample output showing the current incorrect results: a PRINT_MAP call from MAIN +-+ |MAP: NSEWUD| |room1> 50| |room2> 50| |room3> 50| |room4> 50| |room5> 50| |room6> 50| |room7> 50| +-+ = the contents of the data file, mazegame.dat 0 0 0 0 0 0 0 0 0 4 2 0 0 0 0 0 0 1 3 6 0 0 0 5 0 2 0 0 0 1 0 5 0 0 0 0 3 0 0 4 0 7 0 0 0 0 0 0 2 0 0 0 0 0 5 0 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/l
[Tutor] extending a VS python with cygwin
summary: how to fix ... m...@cygwinbox ~/bin/duplicity-0.6.09$ python setup.py install ... > error: Python was built with Visual Studio 2003; > extensions must be built with a compiler than can generate > compatible binaries. Visual Studio 2003 was not found on this > system. If you have Cygwin installed, you can try compiling with > MingW32, by passing "-c mingw32" to setup.py. m...@cygwinbox ~/bin/duplicity-0.6.09$ python -c mingw32 setup.py install > Traceback (most recent call last): > File "", line 1, in > NameError: name 'mingw32' is not defined m...@cygwinbox ~/bin/duplicity-0.6.09$ python setup.py -c mingw32 install > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] >or: setup.py --help [cmd1 cmd2 ...] >or: setup.py --help-commands >or: setup.py cmd --help > error: option -c not recognized m...@cygwinbox ~/bin/duplicity-0.6.09$ python setup.py install -c mingw32 > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] >or: setup.py --help [cmd1 cmd2 ...] >or: setup.py --help-commands >or: setup.py cmd --help > error: invalid command 'mingw32' details: What's the appropriate syntax to solve the above python build problem? Why I ask: I mostly run linux, and I've been using python-based `duplicity` http://duplicity.nongnu.org/ to back that up. I've got an older winxp box (SP3, uptodate with WU) which I keep mostly to run ArcGIS, which has happily run many versions of cygwin (which I keep uptodate) over the years. I'd like to be able to restore my linux home to my cygwin home for the rare occasions when I need to use the winxp box. To do that, I'd like to install duplicity on the cygwin box. That install process (best described by the somewhat downlevel http://blog.khorun.com/2008/09/using-duplicity-on-windows-under-cygwin.html ) works for the install of the prerequisite GnuPGInterface and boto python modules (process=[download tarball, tar xfz, python setup.py install]) but fails for the install of duplicity itself, with the error above: m...@cygwinbox ~/bin/duplicity-0.6.09$ python setup.py install ... > error: Python was built with Visual Studio 2003; Note that I'd cheerfully replace that version of python (the 2.5.2 that shipped with my ArcGIS 9.3), except that I use some ArcGIS extensions which seem to choke on other pythons :-( so I'd prefer to build against that if at all possible. > extensions must be built with a compiler than can generate > compatible binaries. Visual Studio 2003 was not found on this > system. If you have Cygwin installed, you can try compiling with > MingW32, by passing "-c mingw32" to setup.py. I try to take the advice offered, but either it's wrong or I'm missing something: m...@cygwinbox ~/bin/duplicity-0.6.09$ python -c mingw32 setup.py install > Traceback (most recent call last): > File "", line 1, in > NameError: name 'mingw32' is not defined m...@cygwinbox ~/bin/duplicity-0.6.09$ python setup.py -c mingw32 install > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] >or: setup.py --help [cmd1 cmd2 ...] >or: setup.py --help-commands >or: setup.py cmd --help > error: option -c not recognized m...@cygwinbox ~/bin/duplicity-0.6.09$ python setup.py install -c mingw32 > usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] >or: setup.py --help [cmd1 cmd2 ...] >or: setup.py --help-commands >or: setup.py cmd --help > error: invalid command 'mingw32' What's the appropriate syntax here? Or how else should I fix this? Apologies if this is a FAQ. If this is the wrong list/forum/whatever for this query, please direct me appropriately. Note that the duplicity list is apparently not the place, though :-( TIA, Tom Roche ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] os.urandom()
Steven D'Aprano wrote: On Mon, 9 Aug 2010 11:51:34 pm you wrote: (Context: Python 3.x, where strings are unicode.) repr() returns the string representation, not the byte representation. Try this: That's what I was missing. Somehow I assumed it was converting to byte strings. I had assumed that it reverted to /u or /U whenever a character was outside the ASCII range. That would be a direct analog to what seems to happen on byte strings. Does it only escape newlines and single quotes ? a = chr(300) b = repr(a) My prediction is that it will succeed, and not fail. Then try this: print(a) My prediction is that it will fail with UnicodeEncodeError. It is is your terminal that can't display arbitrary Unicode characters, because your terminal have a weird encoding set. Fix the terminal, and you won't have the problem: Any suggestions how to fix the Windows console to interpret utf8? FWIW, my sys.stdout.encoding is cp437. Well, there's your problem. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor