[Tutor] String formatting question with 's'.format()
I'm working through the 'Learn Python' book by Mark Lutz, in this example: somelist = list('SPAM') parts = somelist[0], somelist[-1], somelist[1:3] 'first={0}, last={1}, middle={2}'.format(*parts) first=S, last=M, middle=['P', 'A'] why do we need the '*' at 'parts'. I know we need it, because otherwise it gives an error: Traceback (most recent call last): File pyshell#17, line 1, in module 'first={0}, last={1}, middle={2}'.format(parts) IndexError: tuple index out of range Still, wouldn't python basically see 'parts' and insert the actual tuple instead of the variable 'parts'? How does the machine think? ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting question with 's'.format()
From: tutor-bounces+ramit.prasad=jpmchase@python.org [mailto:tutor-bounces+ramit.prasad=jpmchase@python.org] On Behalf Of eize...@gmail.com Sent: Wednesday, June 08, 2011 3:11 PM To: tutor@python.org Subject: [Tutor] String formatting question with 's'.format() I'm working through the 'Learn Python' book by Mark Lutz, in this example: somelist = list('SPAM') parts = somelist[0], somelist[-1], somelist[1:3] 'first={0}, last={1}, middle={2}'.format(*parts) first=S, last=M, middle=['P', 'A'] why do we need the '*' at 'parts'. I know we need it, because otherwise it gives an error: Traceback (most recent call last): File pyshell#17, line 1, in module 'first={0}, last={1}, middle={2}'.format(parts) IndexError: tuple index out of range Still, wouldn't python basically see 'parts' and insert the actual tuple instead of the variable 'parts'? How does the machine think? When you use {0} and {1} and {2} it looks for 3 variables being passed into it format. Passing *parts tells Python that parts is NOT an argument but instead a list of arguments. *parts is equivalent to 3 variables where: Variable 1 = 'S' Variable 2 = 'M' Variable 3 = ['P', 'A'] The error you see when using parts instead of *parts is basically saying it is looking for 2 more arguments to be passed into the function so that it can replace it. Compare: 'first={0}'.format(parts) first=('S', 'M', ['P', 'A']) 'first={0}'.format(*parts) 'first=S' Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting question with 's'.format()
I see now, that example helps. Basically I use one asterisk to extract a list or a tuple and double asterisks for a dictionary, but I have to provide keys in case of a dictionary, like here: template = '{motto}, {pork} and {food}' a = dict(motto='spam', pork='ham', food='eggs') template.format(**a) 'spam, ham and eggs' Thanks for clearing things up. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting question with 's'.format()
eize...@gmail.com wrote 'first={0}, last={1}, middle={2}'.format(*parts) first=S, last=M, middle=['P', 'A'] why do we need the '*' at 'parts'. I know we need it, because otherwise it gives an error: The * tells Python to unpack parts and treat the contents as individual values. format is looking for 3 values. Without the * it sees one, a tuple and complains about insufficient values. If it did try to do the format you would wind up with something like: first=(S,M,['P', 'A']) last=None, middle=None Python can't tell automatiocally whether you want the tuple treated as a single value and youu just forgot the other two or if you want the tuple unpacked. The * says unpack this value. 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
Re: [Tutor] String formatting question.
Wayne Werner wrote: On Tue, Mar 29, 2011 at 2:41 PM, Prasad, Ramit ramit.pra...@jpmchase.comwrote: Is there a difference (or preference) between using the following? %s %d % (var,num) VERSUS {0} {1}.format(var,num) Practically there's no difference. In reality (and under the hood) there are more differences, some of which are subtle. On the contrary, the two code snippets *explicitly* do different things, about as different as: str(var) + str(int(num)) vs. str(var) + str(num) The first example expects an arbitrary object and a number on the right hand side of the % operator. The second example expects two arbitrary objects. Now, I see from your next comment that you realise this: For instance, in the first example, var = 3, num = 'hi' will error, while with .format, it won't. but you don't make it clear that that's because the two pieces of code ask for two different things, not because of a difference between % and format(). To be consistent, you would compare: %s %s % (var,num) vs. {0} {1}.format(var,num) or possibly: %s %d % (var,num) {0} {1:d}.format(var,num) # I think, I'm stuck here with Python 2.4 # and can't check it. Any other differences? Yes, plenty. % formatting and .format() don't just have different syntax, they have different capabilities. format() has more power, but that power comes at the cost of being slightly slower and being more verbose to write. My personal preference is to use .format() as it (usually) feels more elegant: ({0} *8+{1}).format(na, batman) vs: %s %s % (na * 8, batman) They do different things. The first repeats na separated by spaces; the second has nananana without spaces. In any case, we differ in our opinion of elegant, because I feel the two solutions are equally elegant. And named arguments: Name: {name}\nAddress: {address}.format(name=Bob, address=123 Castle Auuurrggh) vs Name: %(name)\nAddress: %(address) % {name: Bob, address, 123 Castle Auurgh) The second example will not work, because you have forgotten the type code. That's an advantage of % formatting: if you forget the type code, you get an error instead of a default, likely incorrect, type. My recommendation would be to use what feels most natural to you. I think I read somewhere that % formatting is so ingrained that even though the .format() method is intended to replace it, it's probably going to stick around for a while. I should think so... there are plenty of ex-C programmers whose attitude is You can have my % format strings when you pry them from my cold, dead fingers. I'm not a C programmer, and I agree with them. -- Steven ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting question.
IMHO % formatting is the easiest to use and understand. I am sorry that it has been slated for removal. -- 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] String formatting question.
On 31-Mar-11 09:46, bob gailer wrote: IMHO % formatting is the easiest to use and understand. I am sorry that it has been slated for removal. I had the same reaction, but I think it was mostly because of my long background as a C programmer, since it's essentially the equivalent of printf() formatting. Just heavily ingrained in my brain. However, since the more recent Python 2 versions have supported str.format(), and anticipating their removal from Python 3, I have started gravitating more to them, and I have to admit they're more powerful and probably a good evolutionary step to take. Especially so if your formats are configurable or generated by code which may want to reorder the values. -- Steve Willoughby / st...@alchemy.com A ship in harbor is safe, but that is not what ships are built for. PGP Fingerprint 48A3 2621 E72C 31D9 2928 2E8F 6506 DB29 54F7 0F53 ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] String formatting question.
Is there a difference (or preference) between using the following? %s %d % (var,num) VERSUS {0} {1}.format(var,num) Ramit Ramit Prasad | JPMorgan Chase Investment Bank | Currencies Technology 712 Main Street | Houston, TX 77002 work phone: 713 - 216 - 5423 This communication is for informational purposes only. It is not intended as an offer or solicitation for the purchase or sale of any financial instrument or as an official confirmation of any transaction. All market prices, data and other information are not warranted as to completeness or accuracy and are subject to change without notice. Any comments or statements made herein do not necessarily reflect those of JPMorgan Chase Co., its subsidiaries and affiliates. This transmission may contain information that is privileged, confidential, legally privileged, and/or exempt from disclosure under applicable law. If you are not the intended recipient, you are hereby notified that any disclosure, copying, distribution, or use of the information contained herein (including any reliance thereon) is STRICTLY PROHIBITED. Although this transmission and any attachments are believed to be free of any virus or other defect that might affect any computer system into which it is received and opened, it is the responsibility of the recipient to ensure that it is virus free and no responsibility is accepted by JPMorgan Chase Co., its subsidiaries and affiliates, as applicable, for any loss or damage arising in any way from its use. If you received this transmission in error, please immediately contact the sender and destroy the material in its entirety, whether in electronic or hard copy format. Thank you. Please refer to http://www.jpmorgan.com/pages/disclosures for disclosures relating to European legal entities. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting question.
On 03/29/2011 03:41 PM, Prasad, Ramit wrote: Is there a difference (or preference) between using the following? %s %d % (var,num) VERSUS {0} {1}.format(var,num) Ramit If you're using Python 3, use the second one. If you're using Python 2, you have no option but to use the first, as far as I know. Maybe Python 2.7 has that formatting, I'm not sure. -- Corey Richardson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting question.
On Tue, Mar 29, 2011 at 4:21 PM, Corey Richardson kb1...@aim.com wrote: On 03/29/2011 03:41 PM, Prasad, Ramit wrote: Is there a difference (or preference) between using the following? %s %d % (var,num) VERSUS {0} {1}.format(var,num) Ramit If you're using Python 3, use the second one. If you're using Python 2, you have no option but to use the first, as far as I know. Maybe Python 2.7 has that formatting, I'm not sure. -- Corey Richardson ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor you can use string{0}.format(var) in python 2.6. I use it all the time. I never use the other % method. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting question.
On 29/03/2011 20:41, Prasad, Ramit wrote: Is there a difference (or preference) between using the following? %s %d % (var,num) VERSUS {0} {1}.format(var,num) Ramit ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From Python 2.7.1 docs at http://docs.python.org/tutorial/inputoutput.html Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.format() should generally be used.. ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] String formatting question.
For simple strings I use the %s % foo version, for more complex stuff I use the .format() method. I find it easier to control spacing and alignments with the .format() method, but that's just me. -Modulok- On 3/29/11, Blockheads Oi Oi breamore...@yahoo.co.uk wrote: On 29/03/2011 20:41, Prasad, Ramit wrote: Is there a difference (or preference) between using the following? %s %d % (var,num) VERSUS {0} {1}.format(var,num) Ramit ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor From Python 2.7.1 docs at http://docs.python.org/tutorial/inputoutput.html Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.format() should generally be used.. ___ 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] String formatting question.
On Tue, Mar 29, 2011 at 2:41 PM, Prasad, Ramit ramit.pra...@jpmchase.comwrote: Is there a difference (or preference) between using the following? %s %d % (var,num) VERSUS {0} {1}.format(var,num) Practically there's no difference. In reality (and under the hood) there are more differences, some of which are subtle. For instance, in the first example, var = 3, num = 'hi' will error, while with .format, it won't. If you are writing code that should be backwards compatible, pre-2.6, then you should use the % formatting. My personal preference is to use .format() as it (usually) feels more elegant: ({0} *8+{1}).format(na, batman) vs: %s %s % (na * 8, batman) And named arguments: Name: {name}\nAddress: {address}.format(name=Bob, address=123 Castle Auuurrggh) vs Name: %(name)\nAddress: %(address) % {name: Bob, address, 123 Castle Auurgh) But when I'm dealing with floating point, especially if it's a simple output value, I will usually use % formatting: Money left: %8.2f % (money,) vs. Money Left: {0:8.2f).format(money) Of course, it's best to pick a style and stick to it - having something like this: print Name: %s % (name) print Address: {address}.format(address=street) is bad enough, but... print This is %s {0}.format(horrible) % (just) My recommendation would be to use what feels most natural to you. I think I read somewhere that % formatting is so ingrained that even though the .format() method is intended to replace it, it's probably going to stick around for a while. But if you want to be on the safe side, you can always just use .format() - it certainly won't hurt anything, and the fact that it says format is more explicit. If you didn't know Python, you would know that {0} {1} {2}.format(3,2,1) is doing some type of formatting, and since Explicit is better than implicit.*, that should be a good thing. HTH, Wayne * see: import this this.s.encode('rot13').split('\n')[3] ___ Tutor maillist - Tutor@python.org To unsubscribe or change subscription options: http://mail.python.org/mailman/listinfo/tutor
[Tutor] string formatting question
Hello, I'm trying to replace some strings in a line of text, using some regex functions. My question is: If there's more then one regex grouping I want to replace in one line of a file, how can I use the String Formatting operator (%s) in two places? Here's the line it matches in the file: srm:socket portNumber=138 tcpORudp=UDP address=64.41.134.60/ Here's the regex: m_sock = re.compile('(portNumber=)\d+ (tcpORudp=)[A-Z]+') My replace should look like this: \1 112 \2 TCP (obviously 112 and TCP would be varibles) My problem now is how do I construct the replace statement? twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, twork) But of course this does not work! :-( Is there a better way to do this? Or am I just doing this all wrong? Thanks in advance! __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string formatting question
Jerome Jabson wrote: Hello, I'm trying to replace some strings in a line of text, using some regex functions. My question is: If there's more then one regex grouping I want to replace in one line of a file, how can I use the String Formatting operator (%s) in two places? Hi Jerome, I don't understand your question. Can you give a complete example of the line from the file and the new line you want to create? Here's the line it matches in the file: srm:socket portNumber=138 tcpORudp=UDP address=64.41.134.60/ Here's the regex: m_sock = re.compile('(portNumber=)\d+ (tcpORudp=)[A-Z]+') You have put parentheses around fixed strings, so your groups will always be the same. Is that what you want? My replace should look like this: \1 112 \2 TCP (obviously 112 and TCP would be varibles) This looks like you want to make the string portNumber= 112 tcpORudp= TCP but that doesn't have any variable text from the original string so I think I must not understand. Kent My problem now is how do I construct the replace statement? twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, twork) But of course this does not work! :-( Is there a better way to do this? Or am I just doing this all wrong? Thanks in advance! __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string formatting question
My problem now is how do I construct the replace statement? twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, twork) The format operator takes a tuple: twork = m_sock.sub('\1 %s \2 %s' % (port_num, proto), twork) So I removed the comma after the string, used a single percent operator and I put the two variables in a tuple HTH, Alan G Author of the learn to program web tutor http://www.freenetpages.co.uk/hp/alan.gauld ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string formatting question
Hi Kent, Sorry I didn't make my question clearer. Bascially I want to replace this line: srm:socket portNumber=138 tcpORudp=UDP address=64.41.134.60/ With: srm:socket portNumber=2 tcpORudp=TCP address=64.41.134.60/ So the regex grouping are that I want to keep portNumber= and tcpORudp= and replace the values. Which will be varibles in my code. The question is more on the string formatting in the replace. How do use two %s in one statement? i.e.: re.sub('\1 %s \2 %s' % var1 % var2, line) Thanks again! Hello, I'm trying to replace some strings in a line of text, using some regex functions. My question is: If there's more then one regex grouping I want to replace in one line of a file, how can I use the String Formatting operator (%s) in two places? Hi Jerome, I don't understand your question. Can you give a complete example of the line from the file and the new line you want to create? Here's the line it matches in the file: srm:socket portNumber=138 tcpORudp=UDP address=64.41.134.60/ Here's the regex: m_sock = re.compile('(portNumber=)\d+ (tcpORudp=)[A-Z]+') You have put parentheses around fixed strings, so your groups will always be the same. Is that what you want? My replace should look like this: \1 112 \2 TCP (obviously 112 and TCP would be varibles) This looks like you want to make the string portNumber= 112 tcpORudp= TCP but that doesn't have any variable text from the original string so I think I must not understand. Kent My problem now is how do I construct the replace statement? twork = m_sock.sub('\1 %s \2 %s', % port_num % proto, twork) But of course this does not work! :-( Is there a better way to do this? Or am I just doing this all wrong? Thanks in advance! __ Do You Yahoo!? Tired of spam? Yahoo! Mail has the best spam protection around http://mail.yahoo.com ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string formatting question
Jerome Jabson wrote: Hi Kent, Sorry I didn't make my question clearer. Bascially I want to replace this line: srm:socket portNumber=138 tcpORudp=UDP address=64.41.134.60/ With: srm:socket portNumber=2 tcpORudp=TCP address=64.41.134.60/ So the regex grouping are that I want to keep portNumber= and tcpORudp= and replace the values. Which will be varibles in my code. The question is more on the string formatting in the replace. How do use two %s in one statement? i.e.: re.sub('\1 %s \2 %s' % var1 % var2, line) Ok, actually now I can reread your original question and it makes sense :-) I think I'm having an off day for answering questions. I'm glad Alan is with it :-) he gave the answer you need. Kent ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor
Re: [Tutor] string formatting question
On 7 Apr 2006, [EMAIL PROTECTED] wrote: Sorry I didn't make my question clearer. Bascially I want to replace this line: srm:socket portNumber=138 tcpORudp=UDP address=64.41.134.60/ With: srm:socket portNumber=2 tcpORudp=TCP address=64.41.134.60/ So the regex grouping are that I want to keep portNumber= and tcpORudp= and replace the values. Which will be varibles in my code. The question is more on the string formatting in the replace. How do use two %s in one statement? i.e.: re.sub('\1 %s \2 %s' % var1 % var2, line) You could write it simply like that: Python s = 'srm:socket portNumber=138 tcpORudp=UDP address=64.41.134.60/' Python re.sub('.*?','%s',s,2) 'srm:socket portNumber=%s tcpORudp=%s address=64.41.134.60/' Python re.sub('.*?','%s',s,2) % ('1000', 'TCP') 'srm:socket portNumber=1000 tcpORudp=TCP address=64.41.134.60/' Or you could exploit the fact that you can use a function instead of a simply string as substitution; in that function you can do really complicated things. Karl -- Please do *not* send copies of replies to me. I read the list ___ Tutor maillist - Tutor@python.org http://mail.python.org/mailman/listinfo/tutor