Re: String manipulation in python..NEED HELP!!!!
On Tue, 11 Dec 2012 16:39:27 +, duncan smith wrote: [snip] > >>> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" > >>> key = "XPMGTDHLYONZBWEARKJUFSCIQV" > >>> mapping = {} > >>> for i, ch in enumerate(alpha): > mapping[ch] = key[i] mapping = dict(zip(alpha, key)) -- To email me, substitute nowhere->spamcop, invalid->net. -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation in python..NEED HELP!!!!
On 12 December 2012 07:52, Ross Ridge wrote: > John Gordon wrote: > > def encode(plain): > > '''Return a substituted version of the plain text.''' > > encoded = '' > > for ch in plain: > >encoded += key[alpha.index(ch)] > > return encoded > > Terry Reedy wrote: > >The turns an O(n) problem into a slow O(n*n) solution. Much better to > >build a list of chars and then join them. > > There have been much better suggestions in this thread, but John Gordon's > code above is faster than the equivilent list and join implementation > with Python 2.6 and Python 3.1 (the newest versions I have handy). > CPython optimized this case of string concatenation into O(n) back in > Python 2.4. > >From "What's New in Python 2.4": http://docs.python.org/release/2.4.4/whatsnew/node12.html#SECTION000121 String concatenations in statements of the form s = s + "abc" and s += "abc" are now performed more efficiently *in certain circumstances*. This optimization *won't be present in other Python implementations such as Jython*, so you shouldn't rely on it; using the join() method of strings is still recommended when you want to efficiently glue a large number of strings together. Emphasis mine. The optimisation was added to improve the situation for programs that were already using the anti-pattern of string concatenation, not to encourage people to use it. As a real-world case, a bug was recently found in Mercurial where an operation on Windows was taking orders of magnitudes longer than on Linux due to use of string concatenation rather than the join idiom (from ~12 seconds spent on string concatenation to effectively zero). Tim Delaney -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation in python..NEED HELP!!!!
John Gordon wrote: > def encode(plain): > '''Return a substituted version of the plain text.''' > encoded = '' > for ch in plain: >encoded += key[alpha.index(ch)] > return encoded Terry Reedy wrote: >The turns an O(n) problem into a slow O(n*n) solution. Much better to >build a list of chars and then join them. There have been much better suggestions in this thread, but John Gordon's code above is faster than the equivilent list and join implementation with Python 2.6 and Python 3.1 (the newest versions I have handy). CPython optimized this case of string concatenation into O(n) back in Python 2.4. Ross Ridge -- l/ // Ross Ridge -- The Great HTMU [oo][oo] rri...@csclub.uwaterloo.ca -()-/()/ http://www.csclub.uwaterloo.ca/~rridge/ db // -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation in python..NEED HELP!!!!
On 12/10/2012 5:59 PM, John Gordon wrote: def encode(plain): '''Return a substituted version of the plain text.''' encoded = '' for ch in plain: encoded += key[alpha.index(ch)] return encoded The turns an O(n) problem into a slow O(n*n) solution. Much better to build a list of chars and then join them. -- Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation in python..NEED HELP!!!!
On 10/12/12 22:38, qbai...@ihets.org wrote: I need help with a program i am doing. it is a cryptography program. i am given a regular alphabet and a key. i need to use the user input and use the regular alphabet and use the corresponding letter in the key and that becomes the new letter. i have the basic code but need help with how to mainpulate the string to do the encryption/decryption. please help here is my code so far: """ crypto.py Implements a simple substitution cypher """ alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" key = "XPMGTDHLYONZBWEARKJUFSCIQV" def main(): keepGoing = True while keepGoing: response = menu() if response == "1": plain = raw_input("text to be encoded: ") print encode(plain) elif response == "2": coded = raw_input("code to be decyphered: ") print decode(coded) elif response == "0": print "Thanks for doing secret spy stuff with me." keepGoing = False else: print "I don't know what you want to do..." i really need help on how to encrypt it im not sure how to go about doing that please help. >>> alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" >>> key = "XPMGTDHLYONZBWEARKJUFSCIQV" >>> mapping = {} >>> for i, ch in enumerate(alpha): mapping[ch] = key[i] >>> ''.join(mapping[ch] for ch in "ACE") 'XMT' >>> ''.join(mapping[ch] for ch in "WORD") 'CEKG' >>> Duncan -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation in python..NEED HELP!!!!
On Tue, Dec 11, 2012 at 9:38 AM, wrote: > I need help with a program i am doing. it is a cryptography program. i am > given a regular alphabet and a key. i need to use the user input and use the > regular alphabet and use the corresponding letter in the key and that becomes > the new letter. i have the basic code but need help with how to mainpulate > the string to do the encryption/decryption. please help A few starting tips. Firstly, I'm going to assume here that this is a homework question; you haven't said so, but it seems rather more likely than the alternative (that you're actually going to use such an incredibly low-grade cipher and an interactive prompt like this). Please be honest about this; it's okay to ask for help, but we're not here to do your homework for you. (We do NOT want to help you to get a certificate you don't merit, then get a job using that certificate, and then write code that we'll be staring at in our next jobs. There are already more than enough incompetent programmers in the world; I'd rather that you either learn the material for real, or if you can't, fail the course honestly. Sorry if that sounds harsh, but I'm sure you'd rather that I didn't have a certificate entitling me to drive a truck on roads near you/your kids, because I do not know how to drive one safely.) Secondly, putting "NEED HELP" in your subject line doesn't, in fact, help. :) It just makes you sound demanding. So! On to the actual problem. What you need to do is find the letter that corresponds to the one you have. Decryption is the same as encryption but with the "alpha" and "key" switched, so I recommend creating a function that accepts those two as arguments - something like this: clear = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" key = "XPMGTDHLYONZBWEARKJUFSCIQV" def crypt(msg,from,to): # and put your code in here # To encrypt: encrypted = crypt(original, clear, key) # To decrypt: message = crypt(encrypted, key, clear) The details of the encryption you can put together from John's and/or vbr's responses, but make sure you understand the code yourself. For example: What will each of them do with any non-alphabetic characters? Suppose your original message is "HELLO, WORLD!" - what will happen to the comma, space, and exclamation mark? Be sure you know *why* this is how it is, too. If you run into trouble, post your non-working code and exactly how it's not working, and we'll try to help you understand why it's not working. :) In the meantime, here's a document that you may want to familiarize yourself with: http://www.catb.org/esr/faqs/smart-questions.html It's a great explanation of the how and, more importantly, the why of asking questions of volunteer geeks. All the best! ChrisA -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation in python..NEED HELP!!!!
2012/12/10 : > I need help with a program i am doing. it is a cryptography program. i am > given a regular alphabet and a key. i need to use the user input and use the > regular alphabet and use the corresponding letter in the key and that becomes > the new letter. i have the basic code but need help with how to mainpulate > the string to do the encryption/decryption. please help > > here is my code so far: > > > """ crypto.py > Implements a simple substitution cypher > """ > > alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" > key = "XPMGTDHLYONZBWEARKJUFSCIQV" > > def main(): > keepGoing = True > while keepGoing: > response = menu() > if response == "1": > plain = raw_input("text to be encoded: ") > print encode(plain) > elif response == "2": > coded = raw_input("code to be decyphered: ") > print decode(coded) > elif response == "0": > print "Thanks for doing secret spy stuff with me." > keepGoing = False > else: > print "I don't know what you want to do..." > > > > > i really need help on how to encrypt it im not sure how to go about doing > that please help. > -- > http://mail.python.org/mailman/listinfo/python-list Hi, if I understand correctly, for the data shown in the code, you may probably use the translate method of the string (and the corresponding maketrans method); cf.: python 2.7 >>> import string >>> "ABCDEF...VWXYZ".translate(string.maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", >>> "XPMGTDHLYONZBWEARKJUFSCIQV")) 'XPMGTD...SCIQV' >>> python 3.2 >>> "ABCDEF...VWXYZ".translate("".maketrans("ABCDEFGHIJKLMNOPQRSTUVWXYZ", >>> "XPMGTDHLYONZBWEARKJUFSCIQV")) 'XPMGTD...SCIQV' >>> hth, vbr -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation in python..NEED HELP!!!!
In qbai...@ihets.org writes: > """ crypto.py > Implements a simple substitution cypher > """ > alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" > key = "XPMGTDHLYONZBWEARKJUFSCIQV" > def main(): > keepGoing = True > while keepGoing: > response = menu() > if response == "1": > plain = raw_input("text to be encoded: ") > print encode(plain) > elif response == "2": > coded = raw_input("code to be decyphered: ") > print decode(coded) > elif response == "0": > print "Thanks for doing secret spy stuff with me." > keepGoing = False > else: > print "I don't know what you want to do..." > i really need help on how to encrypt it im not sure how to go about doing > that please help. def encode(plain): '''Return a substituted version of the plain text.''' encoded = '' for ch in plain: encoded += key[alpha.index(ch)] return encoded -- John Gordon A is for Amy, who fell down the stairs gor...@panix.com B is for Basil, assaulted by bears -- Edward Gorey, "The Gashlycrumb Tinies" -- http://mail.python.org/mailman/listinfo/python-list
String manipulation in python..NEED HELP!!!!
I need help with a program i am doing. it is a cryptography program. i am given a regular alphabet and a key. i need to use the user input and use the regular alphabet and use the corresponding letter in the key and that becomes the new letter. i have the basic code but need help with how to mainpulate the string to do the encryption/decryption. please help here is my code so far: """ crypto.py Implements a simple substitution cypher """ alpha = "ABCDEFGHIJKLMNOPQRSTUVWXYZ" key = "XPMGTDHLYONZBWEARKJUFSCIQV" def main(): keepGoing = True while keepGoing: response = menu() if response == "1": plain = raw_input("text to be encoded: ") print encode(plain) elif response == "2": coded = raw_input("code to be decyphered: ") print decode(coded) elif response == "0": print "Thanks for doing secret spy stuff with me." keepGoing = False else: print "I don't know what you want to do..." i really need help on how to encrypt it im not sure how to go about doing that please help. -- http://mail.python.org/mailman/listinfo/python-list
Re: string manipulation.
"gerardob" wrote in message news:29276755.p...@talk.nabble.com... I am trying to read an xml using minidom from python library xml.dom This is the xml file: - AB 100 2 -- This is the python code: from xml.dom import minidom doc= minidom.parse("example.xml") resources_section = doc.getElementsByTagName('resources') list_resources = resources_section[0].getElementsByTagName('resource') for r in list_resources: name = r.childNodes[0].nodeValue print name print len(name) - The problem is that the nodeValue stored in the variable 'name' is not "AB" (what i want) but instead it is a string that has length of 8 and it seems it include the tabs and/or other things. How can i get the string "AB" without the other stuff? Thanks. Whitespace in XML is significant. If the file was: AB100 2 You would just read 'AB'. If you don't control the XML file, then: print name.strip() will remove leading and trailing whitespace. -Mark -- http://mail.python.org/mailman/listinfo/python-list
Re: string manipulation.
On 2010-07-27, gerardob wrote: > > I am trying to read an xml using minidom from python library xml.dom > > This is the xml file: > - > > > > AB > 100 > > 2 > > > > > -- > This is the python code: > > from xml.dom import minidom > doc= minidom.parse("example.xml") > resources_section = doc.getElementsByTagName('resources') > list_resources = resources_section[0].getElementsByTagName('resource') > > for r in list_resources: > name = r.childNodes[0].nodeValue > print name > print len(name) > - > The problem is that the nodeValue stored in the variable 'name' is not "AB" > (what i want) but instead it is a string that has length of 8 and it seems > it include the tabs and/or other things. > How can i get the string "AB" without the other stuff? Check out the strip member function. name = r.childNodes[0].nodeValue.strip() -- Neil Cerutti -- http://mail.python.org/mailman/listinfo/python-list
string manipulation.
I am trying to read an xml using minidom from python library xml.dom This is the xml file: - AB 100 2 -- This is the python code: from xml.dom import minidom doc= minidom.parse("example.xml") resources_section = doc.getElementsByTagName('resources') list_resources = resources_section[0].getElementsByTagName('resource') for r in list_resources: name = r.childNodes[0].nodeValue print name print len(name) - The problem is that the nodeValue stored in the variable 'name' is not "AB" (what i want) but instead it is a string that has length of 8 and it seems it include the tabs and/or other things. How can i get the string "AB" without the other stuff? Thanks. -- View this message in context: http://old.nabble.com/string-manipulation.-tp29276755p29276755.html Sent from the Python - python-list mailing list archive at Nabble.com. -- http://mail.python.org/mailman/listinfo/python-list
String manipulation using RE
Hello folks, i have a string eg "(((A:1,B:1):3,C:3):4,((E:1,F:1):2,D:2):4)" now i have to convert this string to "(((A:1,B:1):2,C:3):1,((E:1,F:1):1,D:2):2)" So i used the logic eg. taking the substring "1):3" and converting it to "1):2"(3-1=2) so on for all the similar substrings.But i am not able to replace them back into the original string. This is what my code looks like import re str = "(((A:1,B:1):3,C:3):4,((E:1,F:1):2,D:2):4)" p =re.compile('\d\):\d') # compiling an re object list1 =[] iterator = p.finditer(str) for match in iterator: x = match.group() l = x.split('):') value = int(l[1])-int(l[0]) z= repr(value) rm = l[1] x= x.rstrip(rm) y = x + repr(value) print y I am able to get the desired output further, any help is appreciated Thanks Aditya -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation questions
snip... > >for counter, line in enumerate(fileIN): >newline = line.replace(oldstring, newstring) >if newline != line: >print 'match at line', counter+1 >fileOUT.write(newline) "enumerate" - haven't seen that before. Nice! Thanks -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation questions
goldtech <[EMAIL PROTECTED]> wrote: > Question1: The replace method - If a string does not have the target > replacement "newstring", then newline equals oldstring? Ie. oldstring > is not changed in any way? Seems to be what I observe but just want to > confirm this. Yes. > > Question2: I'm using "line.find(newstring) != -1..." because I want > to print when a replacement happens. Does "line.replace..." report > indirectly somehow when it replaces? Just do the line.replace() and then test for a change. Question 3 (which I'm sure you meant to ask really) ... No, you shouldn't be using a while loop here. Use a for loop and the enumerate builtin: for counter, line in enumerate(fileIN): newline = line.replace(oldstring, newstring) if newline != line: print 'match at line', counter+1 fileOUT.write(newline) -- http://mail.python.org/mailman/listinfo/python-list
String manipulation questions
Hi, Replacing strings in a text (likely an XML) file. Some newbie questions... ... while line: counter=counter+1 if line.find(newstring) != -1: print 'match at line'+str(counter) newline = line.replace(oldstring, newstring) fileOUT.write(newline) line=fileIN.readline() Question1: The replace method - If a string does not have the target replacement "newstring", then newline equals oldstring? Ie. oldstring is not changed in any way? Seems to be what I observe but just want to confirm this. Question2: I'm using "line.find(newstring) != -1..." because I want to print when a replacement happens. Does "line.replace..." report indirectly somehow when it replaces? Thanks P.S. I know I should be using XSLT to transform XML - but the above seems to work for small text changes. -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation
[EMAIL PROTECTED] writes: > On 4 Apr, 21:47, Alexander Schmolck <[EMAIL PROTECTED]> wrote: > > [EMAIL PROTECTED] writes: > > > Thank you very much, your code works perfectly! > > > > One thing I forgot: you might want to make the whitespace handling a bit > > more > > robust/general e.g. by using something along the lines of > > > > set_phrase.replace(' ', r'\w+') Oops, sorry I meant r'\s+'. > > > > 'as > > Hi! > Thanks again... But where must I insert this instruction? If you're sure the code already does what you want you can forget about my remark; I was thinking of transforming individual patterns like so: 'kindest regard' -> r'kindest\w+regard', but it really depends on the details of your spec, which I'm not familiar with. For example you clearly want to do some amount of whitespace normalization (because you use ``.strip()``), but how much? The most extreme you could go is input = " ".join(file.read().split()) # all newlines, tabs, multiple spaces -> " " In which case you don't need to worry about modifying the patterns to take care of possible whitespace variations. Another possibility is that you specify the patterns you want to replace as regexps in the file e.g. \bkind(?:est)?\b\s+regard(?:s)?\b \byours,\b ... In any case I'd suggest the following: think about what possible edge cases your input can contain and how you'd like to handle then; then write them up as unittests (use doctest or unittest and StringIO) and finally modify your code until it passes all the tests. Here are some examples of possible test patterns: - """kindest regard,""" - """kindest regard""" - """kindest\tregard""" - """kind regards" - """mankind regards other species as inferior""" - """... and please send your wife my kindest regards,""" Finally, if you're looking for a programming excercise you could try the following: rather than working on strings and using regexps, work on a "stream" of words (i.e. ["kindest", "regards", ...]) and write your own code to match sequences of words. 'as p.s. BTW, I overlooked the ``.readlines()`` before, but you don't need it -- files are iterable and you also want to hang on to the openend file object so that you can close it when you're done. -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation
On 4 Apr, 21:47, Alexander Schmolck <[EMAIL PROTECTED]> wrote: > [EMAIL PROTECTED] writes: > > Thank you very much, your code works perfectly! > > One thing I forgot: you might want to make the whitespace handling a bit more > robust/general e.g. by using something along the lines of > > set_phrase.replace(' ', r'\w+') > > 'as Hi! Thanks again... But where must I insert this instruction? -- Marco Minerva, [EMAIL PROTECTED] http://blogs.ugidotnet.org/marcom -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation
[EMAIL PROTECTED] writes: > Thank you very much, your code works perfectly! One thing I forgot: you might want to make the whitespace handling a bit more robust/general e.g. by using something along the lines of set_phrase.replace(' ', r'\w+') 'as -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation
On 4 Apr, 17:39, Alexander Schmolck <[EMAIL PROTECTED]> wrote: > All the code is untested, but should give you the idea. > > > > > > [EMAIL PROTECTED] writes: > > Hi all! > > > I have a file in which there are some expressions such as "kindest > > regard" and "yours sincerely". I must create a phyton script that > > checks if a text contains one or more of these expressions and, in > > this case, replaces the spaces in the expression with the character > > "_". For example, the text > > > Yours sincerely, Marco. > > > Must be transformated in: > > > Yours_sincerely, Marco. > > > Now I have written this code: > > > filemw = codecs.open(sys.argv[1], "r", "iso-8859-1").readlines() > > filein = codecs.open(sys.argv[2], "r", "iso-8859-1").readlines() > > > mw = "" > > for line in filemw: > >mw = mw + line.strip() + "|" > > One "|" too many. Generally, use join instead of many individual string +s. > > mwfind_re_string = "(%s)" % "|".join(line.strip() for line in filemw) > > > mwfind_re = re.compile(r"^(" + mw + ")",re.IGNORECASE|re.VERBOSE) > > mwfind_re = re.compile(mwfind_re_string),re.IGNORECASE) > > > mwfind_subst = r"_" > > > for line in filein: > > That doesn't work. What about "kindest\nregard"? I think you're best of > reading the whole file in (don't forget to close the files, BTW). > > >line = line.strip() > >if (line != ""): > >line = mwfind_re.sub(mwfind_subst, line) > >print line > > > It correctly identifies the expressions, but doesn't replace the > > character in the right way. How can I do what I want? > > Use the fact that you can also use a function as a substitution. > > print mwfind_re.sub(lambda match: match.group().replace(' ','_'), > "".join(line.strip() for line in filein)) > > 'as- Nascondi testo tra virgolette - > > - Mostra testo tra virgolette - Hi Alexander! Thank you very much, your code works perfectly! -- Marco Minerva, [EMAIL PROTECTED] http://blogs.ugidotnet.org/marcom -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation
Alexander Schmolck <[EMAIL PROTECTED]> writes: > That doesn't work. What about "kindest\nregard"? I think you're best of > reading the whole file in (don't forget to close the files, BTW). I should have written "that may not always work, depending of whether the set phrases you're interested in can also span lines". If in doubt, it's better to assume they can. 'as -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation
All the code is untested, but should give you the idea. [EMAIL PROTECTED] writes: > Hi all! > > I have a file in which there are some expressions such as "kindest > regard" and "yours sincerely". I must create a phyton script that > checks if a text contains one or more of these expressions and, in > this case, replaces the spaces in the expression with the character > "_". For example, the text > > Yours sincerely, Marco. > > Must be transformated in: > > Yours_sincerely, Marco. > > Now I have written this code: > > filemw = codecs.open(sys.argv[1], "r", "iso-8859-1").readlines() > filein = codecs.open(sys.argv[2], "r", "iso-8859-1").readlines() > > mw = "" > for line in filemw: > mw = mw + line.strip() + "|" One "|" too many. Generally, use join instead of many individual string +s. mwfind_re_string = "(%s)" % "|".join(line.strip() for line in filemw) > mwfind_re = re.compile(r"^(" + mw + ")",re.IGNORECASE|re.VERBOSE) mwfind_re = re.compile(mwfind_re_string),re.IGNORECASE) > mwfind_subst = r"_" > > for line in filein: That doesn't work. What about "kindest\nregard"? I think you're best of reading the whole file in (don't forget to close the files, BTW). > line = line.strip() > if (line != ""): > line = mwfind_re.sub(mwfind_subst, line) > print line > > It correctly identifies the expressions, but doesn't replace the > character in the right way. How can I do what I want? Use the fact that you can also use a function as a substitution. print mwfind_re.sub(lambda match: match.group().replace(' ','_'), "".join(line.strip() for line in filein)) 'as -- http://mail.python.org/mailman/listinfo/python-list
String manipulation
Hi all! I have a file in which there are some expressions such as "kindest regard" and "yours sincerely". I must create a phyton script that checks if a text contains one or more of these expressions and, in this case, replaces the spaces in the expression with the character "_". For example, the text Yours sincerely, Marco. Must be transformated in: Yours_sincerely, Marco. Now I have written this code: filemw = codecs.open(sys.argv[1], "r", "iso-8859-1").readlines() filein = codecs.open(sys.argv[2], "r", "iso-8859-1").readlines() mw = "" for line in filemw: mw = mw + line.strip() + "|" mwfind_re = re.compile(r"^(" + mw + ")",re.IGNORECASE|re.VERBOSE) mwfind_subst = r"_" for line in filein: line = line.strip() if (line != ""): line = mwfind_re.sub(mwfind_subst, line) print line It correctly identifies the expressions, but doesn't replace the character in the right way. How can I do what I want? Thanks in advance. -- Marco Minerva, [EMAIL PROTECTED] http://blogs.ugidotnet.org/marcom -- http://mail.python.org/mailman/listinfo/python-list
Re: python challenge question (string manipulation)
Felipe I get the same results as you. You make a good point about not iterating when it's not needed. I played around with your test code and found some interesting things: 1. enumerate vs. range(len()) has very little overhead (something I have wondered about) In my code, making the change causes the timing to go from 27.5 usec to 24.6 usec: basically nothing. 2. I combined the two result statements into one, and your code as written still appears consistently faster, albeit only slightly: One-line assignment to result: 6.98; 7.18; 6.49; 7.1 (code below) Your way via extend: 5.24; 5.26; 5.09; 5.3; 5.26; 5.21 (code further below) Is this because of "+" concatenation? My one-line assignment to result: [EMAIL PROTECTED] ~]$ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first =(-n) % length; result = list(lst[first:]) + list(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10 loops, best of 3: 6.98 usec per loop [EMAIL PROTECTED] ~]$ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first =(-n) % length; result = list(lst[first:]) + list(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10 loops, best of 3: 7.18 usec per loop [EMAIL PROTECTED] ~]$ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first =(-n) % length; result = list(lst[first:]) + list(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10 loops, best of 3: 6.49 usec per loop [EMAIL PROTECTED] ~]$ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first =(-n) % length; result = list(lst[first:]) + list(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10 loops, best of 3: 7.1 usec per loop Your code: [EMAIL PROTECTED] ~]$ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first =(-n) % length; result = list(lst[first:]); result.extend(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10 loops, best of 3: 5.24 usec per loop [EMAIL PROTECTED] ~]$ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first =(-n) % length; result = list(lst[first:]); result.extend(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10 loops, best of 3: 5.26 usec per loop [EMAIL PROTECTED] ~]$ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first =(-n) % length; result = list(lst[first:]); result.extend(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10 loops, best of 3: 5.09 usec per loop [EMAIL PROTECTED] ~]$ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first =(-n) % length; result = list(lst[first:]); result.extend(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10 loops, best of 3: 5.3 usec per loop [EMAIL PROTECTED] ~]$ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first =(-n) % length; result = list(lst[first:]); result.extend(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10 loops, best of 3: 5.26 usec per loop [EMAIL PROTECTED] ~]$ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first =(-n) % length; result = list(lst[first:]); result.extend(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10 loops, best of 3: 5.21 usec per loop Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: python challenge question (string manipulation)
Em Qua, 2006-03-29 às 22:20 -0800, Caleb Hattingh escreveu: > That is very succint. Rewriting my shift function given earlier: > > >>> import string > >>> alpha = string.ascii_lowercase > >>> print alpha > abcdefghijklmnopqrstuvwxyz > >>> def shift(lst, n): > return [lst[(i+len(lst)-n)%len(lst)] for i,item in enumerate(lst)] It sure is short, but is it fast? Compare to the function below (the fastest I can think of ATM): def shift(lst, n): first = (-n) % len(lst) result = list(lst[first:]) # if lst is a iterable but not a list result.extend(lst[:first]) return result Now benchmarking: $ python2.4 -mtimeit -s "def shift(lst, n): return [lst[(i+len(lst)-n)% len(lst)] for i,item in enumerate(lst)]" "shift('abcdefghijklmnopqrstuvwxyz',2)" 1 loops, best of 3: 21.5 usec per loop $ python2.4 -mtimeit -s "def shift(lst, n): length = len(lst); first = (-n) % length; result = list(lst[first:]); result.extend(lst[:first]); return result" "shift('abcdefghijklmnopqrstuvwxyz',2)" 10 loops, best of 3: 3.98 usec per loop The five-line version is more than five times faster than the two-line counterpart. But it scales better too: $ python2.4 -mtimeit -s "string = 'abcdefghijklmnopqrstuvwxyz'*1 def shift(lst, n): length = len(lst); first = (-n) % length; result = list(lst[first:]); result.extend(lst[:first]); return result" "shift(string,2)" 100 loops, best of 3: 10.6 msec per loop $ python2.4 -mtimeit -s "string = 'abcdefghijklmnopqrstuvwxyz'*1 def shift(lst, n): return [lst[(i+len(lst)-n)%len(lst)] for i,item in enumerate(lst)]" "shift(string,2)" 10 loops, best of 3: 206 msec per loop With a 10 000 times larger list it takes almost 20 times less time. Of course a human can't perceive a 17.52 usec difference in time, but I'd like to make it clear that the two-line function shouldn't be used on a real system. What we learn from this? When it's not needed (like now), please don't iterate over all items of a list. HTH, -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: python challenge question (string manipulation)
Terry That is very succint. Rewriting my shift function given earlier: >>> import string >>> alpha = string.ascii_lowercase >>> print alpha abcdefghijklmnopqrstuvwxyz >>> def shift(lst, n): return [lst[(i+len(lst)-n)%len(lst)] for i,item in enumerate(lst)] >>> print shift(alpha,2) ['y', 'z', 'a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i', 'j', 'k', 'l', 'm', 'n', 'o', 'p', 'q', 'r', 's', 't', 'u', 'v', 'w', 'x'] Shorter and possibly as clear too; thanks! Keep well Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: python challenge question (string manipulation)
"John Salerno" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > John Salerno wrote: > >> It works, but is there a better way to shift the letters of the alphabet >> for 'code'? I remember a method that did this for lists, I think, but I >> can't remember what it was or if it worked for strings. > > Ah ha! This is cleaner: > > alphabet = string.ascii_lowercase > code = string.ascii_lowercase[2:] + string.ascii_lowercase[:2] > > Yet it still seems kind of verbose. But since that's the official > solution, I guess there's no other way to shift the characters in a > string? The above would look less verbose if the second line 'paid attention' to the first and were written as the slightly more efficient code = alphabet[2:] + alphabet[:2] An alternative is shifted access. alphabet[(i+24)%26] Terry Jan Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: python challenge question (string manipulation)
Em Qua, 2006-03-29 às 19:34 +, John Salerno escreveu: > alphabet = string.ascii_lowercase > code = string.ascii_lowercase[2:] + string.ascii_lowercase[:2] > > Yet it still seems kind of verbose. But since that's the official > solution, I guess there's no other way to shift the characters in a string? --- from collections import deque from string import ascii_lowercase a = deque(ascii_lowercase) a.rotate(-2) print list(a) # prints ['c', 'd', ..., 'z', 'a', 'b'] --- But mind the performance! (as an exercise, time the performance of mine and your approach using the timeit module and post back to the list) HTH, -- Felipe. -- http://mail.python.org/mailman/listinfo/python-list
Re: python challenge question (string manipulation)
Caleb Hattingh wrote: > Also, I suspect you meant to say: > alphabet = string.ascii_lowercase code = alphabet[2:] + alphabet[:2] Ah yes, I see what you did there. :) > I actually create a new list here, although since lists are mutable, I > could probably just change items in-place. There is very likely > something already in the builtins or the standard library for this, but > I just haven't searched hard enough. I'm pretty sure I read about a method for moving the items in lists around like that, so that you can shift the beginning to the end and vice versa. If I can find it, I'll let you know. -- http://mail.python.org/mailman/listinfo/python-list
Re: python challenge question (string manipulation)
John In python, strings are immutable - you have to create a new string no matter what you do. Also, I suspect you meant to say: >>> alphabet = string.ascii_lowercase >>> code = alphabet[2:] + alphabet[:2] I had a similar need recently for a guitar chord generator program I've been working on. Here is a "shift" function from my utilities module: def shift(list,num): '''Shifts sequence "list" by "num" places. if num is positive, list scrolls forwards, otherwise, backwards.''' if abs(num) > len(list): num=num%len(list) # Use mod to remove full list entry rotations newlist=list[-num:]+list[:-num] return newlist I actually create a new list here, although since lists are mutable, I could probably just change items in-place. There is very likely something already in the builtins or the standard library for this, but I just haven't searched hard enough. Interesting trap I kept falling into: calling a guitar string a "string" and then having collisions with the python type of the same name. Over and over again :) Regards Caleb -- http://mail.python.org/mailman/listinfo/python-list
Re: python challenge question (string manipulation)
John Salerno wrote: > It works, but is there a better way to shift the letters of the alphabet > for 'code'? I remember a method that did this for lists, I think, but I > can't remember what it was or if it worked for strings. Ah ha! This is cleaner: alphabet = string.ascii_lowercase code = string.ascii_lowercase[2:] + string.ascii_lowercase[:2] Yet it still seems kind of verbose. But since that's the official solution, I guess there's no other way to shift the characters in a string? -- http://mail.python.org/mailman/listinfo/python-list
python challenge question (string manipulation)
Ok, for those who have gotten as far as level 2 (don't laugh!), I have a question. I did the translation as such: import string alphabet = string.lowercase[:26] code = string.lowercase[2:26] + 'ab' clue = "g fmnc wms bgblr rpylqjyrc gr zw fylb. rfyrq ufyr amknsrcpq ypc dmp. bmgle gr gl zw fylb gq glcddgagclr ylb rfyr'q ufw rfgq rcvr gq qm jmle. sqgle qrpgle.kyicrpylq() gq pcamkkclbcb. lmu ynnjw ml rfc spj." trans = string.maketrans(alphabet, code) clue = clue.translate(trans) print clue raw_input() It works, but is there a better way to shift the letters of the alphabet for 'code'? I remember a method that did this for lists, I think, but I can't remember what it was or if it worked for strings. Thanks. -- http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation Help!
"Richard Schneiderman" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > I really enjoyed your article. I will try to understand this. > Will you be doing more of this in the future with more complicated examples? > I'm giving two presentations at PyCon at the end of February, so I think those will be published after the conference. Otherwise, I'll be answering pyparsing questions as they come up on c.l.py or on the pyparsing forums on SourceForge. I'd like to compile these into more of a book form at some point, but my work schedule is pretty crazy right now. Glad you liked the article, -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation Help!
I really enjoyed your article. I will try to understand this. Will you be doing more of this in the future with more complicated examples? Paul McGuire wrote: > "Dave" <[EMAIL PROTECTED]> wrote in message > news:[EMAIL PROTECTED] >> OK, I'm stumped. >> >> I'm trying to find newline characters (\n, specifically) that are NOT >> in comments. >> >> So, for example (where "<-" = a newline character): >> == >> 1: <- >> 2: /*<- >> 3: --<- >> 4: comment<- >> 5: --<- >> 6: */<- >> 7: <- >> 8: CODE CODE CODE<- >> 9: <- >> == >> >> I want to return the newline characters at lines 1, 6, 7, 8, and 9 but >> NOT the others. >> > > Dave - > > Pyparsing has built-in support for detecting line breaks and comments, and > the syntax is pretty simple, I think. Here's a pyparsing program that > gives your desired results: > > === > from pyparsing import lineEnd, cStyleComment, lineno > > testsource = """ > /* > -- > comment > -- > */ > > CODE CODE CODE > > """ > > # define the expression you want to search for > eol = lineEnd > > # specify that you don't want to match within C-style comments > eol.ignore(cStyleComment.leaveWhitespace()) > > # loop through all the occurrences returned by scanString > # and print the line number of that location within the original string > for toks,startloc,endloc in eol.scanString(testsource): > print lineno(startloc,data) > === > > The expression you are searching for is pretty basic, just a plain > end-of-line, or pyparsing's built-in expression, lineEnd. The curve you > are throwing is that you *don't* want eol's inside of C-style comments. > Pyparsing allows you to designate an "ignore" expression to skip > undesirable content, and fortunately, ignoring comments happens so often > during parsing, that pyparsing includes common comment expressions for C, > C++, Java, Python, > and HTML. Next, pyparsing's version of re.search is scanString. > scanString returns a generator that gives the matching tokens, start > location, and end location of every occurrence of the given parse > expression, in your case, > eol. Finally, in the body of our for loop, we use pyparsing's lineno > function to give us the line number of a string location within the > original string. > > About the only real wart on all this is that pyparsing implicitly skips > over > leading whitespace, even when looking for expressions to be ignored. In > order not to lose eols that are just before a comment (like your line 1), > we have to modify cStyleComment to leave leading whitespace. > > Download pyparsing at http://pyparsing.sourceforge.net. > > -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation Help!
"Dave" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > OK, I'm stumped. > > I'm trying to find newline characters (\n, specifically) that are NOT > in comments. > > So, for example (where "<-" = a newline character): > == > 1: <- > 2: /*<- > 3: --<- > 4: comment<- > 5: --<- > 6: */<- > 7: <- > 8: CODE CODE CODE<- > 9: <- > == > > I want to return the newline characters at lines 1, 6, 7, 8, and 9 but > NOT the others. > Dave - Pyparsing has built-in support for detecting line breaks and comments, and the syntax is pretty simple, I think. Here's a pyparsing program that gives your desired results: === from pyparsing import lineEnd, cStyleComment, lineno testsource = """ /* -- comment -- */ CODE CODE CODE """ # define the expression you want to search for eol = lineEnd # specify that you don't want to match within C-style comments eol.ignore(cStyleComment.leaveWhitespace()) # loop through all the occurrences returned by scanString # and print the line number of that location within the original string for toks,startloc,endloc in eol.scanString(testsource): print lineno(startloc,data) === The expression you are searching for is pretty basic, just a plain end-of-line, or pyparsing's built-in expression, lineEnd. The curve you are throwing is that you *don't* want eol's inside of C-style comments. Pyparsing allows you to designate an "ignore" expression to skip undesirable content, and fortunately, ignoring comments happens so often during parsing, that pyparsing includes common comment expressions for C, C++, Java, Python, and HTML. Next, pyparsing's version of re.search is scanString. scanString returns a generator that gives the matching tokens, start location, and end location of every occurrence of the given parse expression, in your case, eol. Finally, in the body of our for loop, we use pyparsing's lineno function to give us the line number of a string location within the original string. About the only real wart on all this is that pyparsing implicitly skips over leading whitespace, even when looking for expressions to be ignored. In order not to lose eols that are just before a comment (like your line 1), we have to modify cStyleComment to leave leading whitespace. Download pyparsing at http://pyparsing.sourceforge.net. -- Paul -- http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation Help!
This is great, thanks! -- http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation Help!
Dave wrote: > OK, I'm stumped. > > I'm trying to find newline characters (\n, specifically) that are NOT > in comments. > > So, for example (where "<-" = a newline character): > == > 1: <- > 2: /*<- > 3: --<- > 4: comment<- > 5: --<- > 6: */<- > 7: <- > 8: CODE CODE CODE<- > 9: <- > == [snip] Well, I'm sure there is some regex that'll do it, but here's a stupid iterative solution: def newlines(s): nl = [] inComment = False for i in xrange(len(s)): if s[i:i+2] == '/*': inComment = True if s[i:i+2] == '*/': inComment = False if inComment: continue if s[i] == '\n': nl.append(i) return tuple(nl) Your example returns: (0, 64, 65, 80, 81) This probably isn't as fast as a regex, but at least it works. -Kirk McDonald -- http://mail.python.org/mailman/listinfo/python-list
String Manipulation Help!
OK, I'm stumped. I'm trying to find newline characters (\n, specifically) that are NOT in comments. So, for example (where "<-" = a newline character): == 1: <- 2: /*<- 3: --<- 4: comment<- 5: --<- 6: */<- 7: <- 8: CODE CODE CODE<- 9: <- == I want to return the newline characters at lines 1, 6, 7, 8, and 9 but NOT the others. I've tried using regular expressions but I dislike them because they aren't immediately readable (and also I don't bloody understand the things). I'm not opposed to using them, though, if they provide a solution to this problem! Thanks in advance for any suggestions anyone can provide. - Dave -- http://mail.python.org/mailman/listinfo/python-list
Re: Filepath string manipulation help
I just assumed he had heard of me and knew better than to take my advice. :-) -- http://mail.python.org/mailman/listinfo/python-list
Re: Filepath string manipulation help
mjakowlew wrote: > Steve, > > the os commands don't run through zope, it denies access to them to be > run at all through the webserver. So in turn, I had to use a work > around to fix the IE problem. Also qwwee's suggestion to use: > > filepath.split('\\')[-1] > > works well too. Zope is very finicky about running specific commands, > I'm sure this is due to security issues of running os commands through > a website/webserver. > That's a good enough reason. You are excused. :-) regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Filepath string manipulation help
Steve, the os commands don't run through zope, it denies access to them to be run at all through the webserver. So in turn, I had to use a work around to fix the IE problem. Also qwwee's suggestion to use: filepath.split('\\')[-1] works well too. Zope is very finicky about running specific commands, I'm sure this is due to security issues of running os commands through a website/webserver. -- http://mail.python.org/mailman/listinfo/python-list
Re: Filepath string manipulation help
mjakowlew wrote: > I got the "IE Fix" working, here's the code: > > > path = r'c:\here\there\files\file.ext' > > i=len(path) > j=0 > size=len(path) > > while i: > i=i-1 > if path[i]== '\\': > j=i+1 > break > > filename = path[j:size] > print "FILENAME: %s" %(filename) > ___ > > Most importantly this works on my Zope webserver. > > Thanks again, > mjakowlew > Is there some reason for preferring this to the fully portable import os print os.path.basename(filepath) that Robert Dowell suggested in immediate response to your post? regards Steve -- Steve Holden +44 150 684 7255 +1 800 494 3119 Holden Web LLC www.holdenweb.com PyCon TX 2006 www.python.org/pycon/ -- http://mail.python.org/mailman/listinfo/python-list
Re: Filepath string manipulation help
I got the "IE Fix" working, here's the code: path = r'c:\here\there\files\file.ext' i=len(path) j=0 size=len(path) while i: i=i-1 if path[i]== '\\': j=i+1 break filename = path[j:size] print "FILENAME: %s" %(filename) ___ Most importantly this works on my Zope webserver. Thanks again, mjakowlew -- http://mail.python.org/mailman/listinfo/python-list
Re: Filepath string manipulation help
Hi mjakowlew, to get file basename in Linux I use simply: filepath.split('/')[-1] But in Windows, being the dir separator '\', you get into trouble if the dir or file name begins with one of the "escape sequences": \a ASCII Bell(BEL) \x07 \b ASCII Backspace (BS) \x08 \f ASCII Formfeed(FF) \x0c \n ASCII Linefeed(LF) \r ASCII Carriage Return (CR) \t ASCII Horizontal Tab (TAB) \v ASCII Vertical Tab(VT) \x0b (from the ref. suggested by Fredrik Lund). To solve the problem you must use "raw strings", as suggested by the aforementioned expert. So your filepath ('c:\documents\web\zope\file.ext') becomes r'c:\documents\web\zope\file.ext' which protects the '\' by escaping it ('\\'). With such a trick you can obtain the file basename with: filepath.split('\\')[-1]. Bye. -- http://mail.python.org/mailman/listinfo/python-list
Re: Filepath string manipulation help
Thanks guys. The os.path method works, but this is for a script for a website upload program on a zope webserver. For some reason even admin access won't let me run the script through the server. The main issue with my script is that Firefox has no problem with the program the way it is, but IE somehow uses a different filename format. ex:/ In IE filepath='c:\documents\web\zope\file.ext' In Firefox filepath='file.ext' So when IE goes to upload the file, it gets an error for illegal characters because of the "\"'s and ":" Is there another way to do this (extract just the filename) using something else other than the "os" that won't be blocked by the webserver -- http://mail.python.org/mailman/listinfo/python-list
Re: Filepath string manipulation help
"mjakowlew"wrote: > filepath='c:\documents\web\zope\file.ext' > > I need to extract everthing after the last '\' and save it. that string doesn't contain what you think it does: >>> filepath='c:\documents\web\zope\file.ext' >>> filepath 'c:\\documents\\web\\zope\x0cile.ext' >>> print filepath c:\documents\web\zope?ile.ext if you fix that, you can use os.path.basename() to strip off the last part: >>> filepath=r'c:\documents\web\zope\file.ext' >>> filepath 'c:\\documents\\web\\zope\\file.ext' >>> print filepath c:\documents\web\zope\file.ext >>> import os >>> os.path.basename(filepath) 'file.ext' for more info on Python's string literal syntax, see section 3.1.2 in the Python Tutorial, and this page: http://docs.python.org/ref/strings.html -- http://mail.python.org/mailman/listinfo/python-list
Re: Filepath string manipulation help
import os print os.path.basename(filepath) -- http://mail.python.org/mailman/listinfo/python-list
Filepath string manipulation help
Hi, I'm trying to use some string manipulation from a file's path. filepath='c:\documents\web\zope\file.ext' I need to extract everthing after the last '\' and save it. I've looked around and have tried the sub, search, match commands, but I'm guessing '\' is set aside for switches. I need to know how to search for the '\' in a string. I'm guessing it has something to do with ASCII char codes. Thanks in advance for any help, mjakowlew -- http://mail.python.org/mailman/listinfo/python-list
Re: help in simplification of code [string manipulation]
But ur previous solution worked on my machine... although a friend tried it on his machine and the libraries were not found even if they existed! (Even the -lm was not found) Can you explain a bit why the previous solution worked? Thanks for ur help, --j -- http://mail.python.org/mailman/listinfo/python-list
Re: help in simplification of code [string manipulation]
John a écrit : > Thanks for your replies... > Solved my problem. Even so, I made a big mistake here. The Split function is of no use because there is already a list of flags. Better do it like that : libs = Split('glut GLU GL m') env.Append (LIBS = libs) BTW, Split is a scons function. > Christophe wrote: > >>John a écrit : >> >>>How could I simplify the code to get libs out of LDFLAGS >>>or vice versa automatically in the following python/scons code? >>> >>>if sys.platform[:5] == 'linux': >>> env.Append (CPPFLAGS = '-D__LINUX') >>> env.Append (LDFLAGS = '-lglut -lGLU -lGL -lm') >>> env.Append(CPPPATH=['include', 'include/trackball']) >>> libs = ['glut', >>> 'GLU', >>> 'GL', >>> 'm',] >>> >>> >>>Thanks, >>>--j >>> >> >>Why don't you use the LIBS var in the environment instead of the LDFLAGS >>? And what use would be the libs var for you ? >> >>if sys.platform[:5] == 'linux': >> libs = ['glut', >> 'GLU', >> 'GL', >> 'm',] >> env.Append (CPPFLAGS = '-D__LINUX') >> env.Append (LIBS = Split(libs)) >> env.Append(CPPPATH=['include', 'include/trackball']) > > -- http://mail.python.org/mailman/listinfo/python-list
Re: help in simplification of code [string manipulation]
Thanks for your replies... Solved my problem. --j Christophe wrote: > John a écrit : > > How could I simplify the code to get libs out of LDFLAGS > > or vice versa automatically in the following python/scons code? > > > > if sys.platform[:5] == 'linux': > > env.Append (CPPFLAGS = '-D__LINUX') > > env.Append (LDFLAGS = '-lglut -lGLU -lGL -lm') > > env.Append(CPPPATH=['include', 'include/trackball']) > > libs = ['glut', > > 'GLU', > > 'GL', > > 'm',] > > > > > > Thanks, > > --j > > > > Why don't you use the LIBS var in the environment instead of the LDFLAGS > ? And what use would be the libs var for you ? > > if sys.platform[:5] == 'linux': > libs = ['glut', > 'GLU', > 'GL', > 'm',] > env.Append (CPPFLAGS = '-D__LINUX') > env.Append (LIBS = Split(libs)) > env.Append(CPPPATH=['include', 'include/trackball']) -- http://mail.python.org/mailman/listinfo/python-list
Re: help in simplification of code [string manipulation]
John a écrit : > How could I simplify the code to get libs out of LDFLAGS > or vice versa automatically in the following python/scons code? > > if sys.platform[:5] == 'linux': > env.Append (CPPFLAGS = '-D__LINUX') > env.Append (LDFLAGS = '-lglut -lGLU -lGL -lm') > env.Append(CPPPATH=['include', 'include/trackball']) > libs = ['glut', > 'GLU', > 'GL', > 'm',] > > > Thanks, > --j > Why don't you use the LIBS var in the environment instead of the LDFLAGS ? And what use would be the libs var for you ? if sys.platform[:5] == 'linux': libs = ['glut', 'GLU', 'GL', 'm',] env.Append (CPPFLAGS = '-D__LINUX') env.Append (LIBS = Split(libs)) env.Append(CPPPATH=['include', 'include/trackball']) -- http://mail.python.org/mailman/listinfo/python-list
Re: help in simplification of code [string manipulation]
John wrote: > How could I simplify the code to get libs out of LDFLAGS > or vice versa automatically in the following python/scons code? > > if sys.platform[:5] == 'linux': > env.Append (CPPFLAGS = '-D__LINUX') > env.Append (LDFLAGS = '-lglut -lGLU -lGL -lm') > env.Append(CPPPATH=['include', 'include/trackball']) > libs = ['glut', > 'GLU', > 'GL', > 'm',] >>> LDFLAGS = '-lglut -lGLU -lGL -lm' >>> libs = [flag[2:] for flag in LDFLAGS.split()] >>> libs ['glut', 'GLU', 'GL', 'm'] Kent -- http://mail.python.org/mailman/listinfo/python-list
help in simplification of code [string manipulation]
How could I simplify the code to get libs out of LDFLAGS or vice versa automatically in the following python/scons code? if sys.platform[:5] == 'linux': env.Append (CPPFLAGS = '-D__LINUX') env.Append (LDFLAGS = '-lglut -lGLU -lGL -lm') env.Append(CPPPATH=['include', 'include/trackball']) libs = ['glut', 'GLU', 'GL', 'm',] Thanks, --j -- http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation
Hi, > for punctuation in punctuations: > line=line.replace(punctuation,'') I would use maketrans or even a regex instead. However, If you care about speed, it is well known that in some cases regex take more time than multiple replaces. Even the maketrans could take more time (I don't know; you may benchmark it -> homework) Regards, Josef -- http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation
On 13 Jul 2005 07:49:02 -0700, Michael Jordan <[EMAIL PROTECTED]> wrote: > hey, i have this huge text file and i need to go through and remove all > punctuation and every instance of the phrase "fruitloops=$" where $ is > any number 0-100" um, and yeah this is homework but i've tried to no > avail. thanks guys. cheerio :). jen Jen, This program iterates through one file and outputs all lines to another file which have the word "homework" in them. #-- Begin program 1 file_in = file('data.in') file_out = file('data.out') for line in file_in: #line is a string containing one line of the file if "homework" in line: file_out.write("homework") #--- End program 1 Here is a program which turns a string containing the phrase "number=42" into a variable containing the integer 42: #-- Begin program 2 #create a string variable called x x = "number=42" #split the string at the '=', resulting in ['number', '42'] n = x.split('=')[1] #turn n from a string into a number, so we could test its value n = int(n) if 0 < n < 100: print "n is between 0 and 100" else: print "n is not between 0 and 100" #-- End program 2 And, finally, a program to remove punctuation from a string: # Begin program 3 import string #create a sentence with punctuation punct = "This. is a, sentence with - punctuation" #remove the punctuation; make sure the first argument #to maketrans is the same length as the second, which #should be all blanks punct = punct.translate(string.maketrans('.,-', ' ')) #read the docs at # http://docs.python.org/lib/node109.html # for more details #End program 3 Hope this helps; you should be able to put the pieces together to do what you want to do. If you can't, feel free to ask more questions. Also, just so you know, there is a list at tutor@python.org set up just to answer questions like these. Peace Bill Mill [EMAIL PROTECTED] -- http://mail.python.org/mailman/listinfo/python-list
Re: String Manipulation
Use .replace function to replace punctuation (you didn't say exactly what that means but just to get you started): # # Extend this list as needed # punctuations=',.;:()' # # Open input and output files # ifp=open(inputfilename,'r') ofp=open(outputfilename,'w') # # Strip out the punctuation characters # for line in ifp: for punctuation in punctuations: line=line.replace(punctuation,'') ofp.write(line) # # I'll leave the other part for homework but # you will need to use the .find method of the string # ifp.close() ofp.close() Larry Bates Michael Jordan wrote: > i'll be straight with you and say that this is a homework assignment. > ive tried to figure it out on my own but am now out of time. > > i need to go through a .txt file and get rid of all punctuation. also, > every time i see the work "Fruitloops=1" or "Hamburgers=x" where x is > ANY number i need to get rid of that also. thanks a bunch. hurry > please! > > jen :) > -- http://mail.python.org/mailman/listinfo/python-list
String Manipulation
hey, i have this huge text file and i need to go through and remove all punctuation and every instance of the phrase "fruitloops=$" where $ is any number 0-100" um, and yeah this is homework but i've tried to no avail. thanks guys. cheerio :). jen -- http://mail.python.org/mailman/listinfo/python-list
String Manipulation
i'll be straight with you and say that this is a homework assignment. ive tried to figure it out on my own but am now out of time. i need to go through a .txt file and get rid of all punctuation. also, every time i see the work "Fruitloops=1" or "Hamburgers=x" where x is ANY number i need to get rid of that also. thanks a bunch. hurry please! jen :) -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation
"vincent wehren" <[EMAIL PROTECTED]> wrote in message news:[EMAIL PROTECTED] > "Nicholas Graham" > | Any suggestions? > Take a look at the built-in functions ord() and chr() > -- Chapter 2.1 of the manual. And more generally, read all of Chap.2 of the Library Reference on builtin functions and types. Later chapters, most of them, are 'look up when you need to' type stuff, but C.2 is core material that everyone should read after the tutorial. Terry J. Reedy -- http://mail.python.org/mailman/listinfo/python-list
Re: String manipulation
"Nicholas Graham" <[EMAIL PROTECTED]> schrieb im Newsbeitrag news:[EMAIL PROTECTED] | | I'm writing a program that requires some string manipulations. Let's say | I have a string | | s='x' | | Now, the ascii code for 'x' is 0x78. I want to be able to perform | operations on this number, and print the character corresponding to the | results of the operation. For example, the pseudo-code looks like: | | -read in string s from external file (for simplicity, we'll keep s='x') | | -determine the code for s (should be 0x78 or 120 in base 10), store it in | variable c | | -add a literal to c (let's say c=c+1) | | -find out which character corresponds to the new code c=0x79 | | -store the character in a new string s2 | | At the end of this, I want s2='y' | | Any suggestions? Take a look at the built-in functions ord() and chr() -- Chapter 2.1 of the manual. >> s = 'x' >> c = ord(s) >> c 120 >> c+=1 >> s2 = chr(c) >> s2 'y' -- Vincent Wehren | | NG | -- http://mail.python.org/mailman/listinfo/python-list
String manipulation
I'm writing a program that requires some string manipulations. Let's say I have a string s='x' Now, the ascii code for 'x' is 0x78. I want to be able to perform operations on this number, and print the character corresponding to the results of the operation. For example, the pseudo-code looks like: -read in string s from external file (for simplicity, we'll keep s='x') -determine the code for s (should be 0x78 or 120 in base 10), store it in variable c -add a literal to c (let's say c=c+1) -find out which character corresponds to the new code c=0x79 -store the character in a new string s2 At the end of this, I want s2='y' Any suggestions? NG -- http://mail.python.org/mailman/listinfo/python-list