473,396 Members | 2,009 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,396 software developers and data experts.

question regarding '%x' %...

TMS
119 100+
if you type print "%x" % (2 + 7 + 5) in the python shell, an 'e' is returned. Can someone explain to me what is going on and why '%y' won't work? With y I get a value error: unsupported format character 'y' (0x79) at index 1. I thought it was like a namespace in C++ where the alphabet was the namespace and when using % the remainder is what is shown. But I don't think that is what it is, because I can't use y.

TMS
Jan 24 '07 #1
4 2275
bartonc
6,596 Expert 4TB
if you type print "%x" % (2 + 7 + 5) in the python shell, an 'e' is returned. Can someone explain to me what is going on and why '%y' won't work? With y I get a value error: unsupported format character 'y' (0x79) at index 1. I thought it was like a namespace in C++ where the alphabet was the namespace and when using % the remainder is what is shown. But I don't think that is what it is, because I can't use y.

TMS
In the Documentation, it says:
Expand|Select|Wrap|Line Numbers
  1. 2.3.6.2 String Formatting Operations 
  2.  
  3. String and Unicode objects have one unique built-in operation: the % operator (modulo). This is also known as the string formatting or interpolation operator. Given format % values (where format is a string or Unicode object), % conversion specifications in format are replaced with zero or more elements of values. The effect is similar to the using sprintf() in the C language. If format is a Unicode object, or if any of the objects being converted using the %s conversion are Unicode objects, the result will also be a Unicode object. 
  4.  
  5. If format requires a single argument, values may be a single non-tuple object.2.8 Otherwise, values must be a tuple with exactly the number of items specified by the format string, or a single mapping object (for example, a dictionary). 
  6.  
  7. A conversion specifier contains two or more characters and has the following components, which must occur in this order: 
  8.  
  9.  
  10. The "%" character, which marks the start of the specifier. 
  11. Mapping key (optional), consisting of a parenthesised sequence of characters (for example, (somename)). 
  12. Conversion flags (optional), which affect the result of some conversion types. 
  13. Minimum field width (optional). If specified as an "*" (asterisk), the actual width is read from the next element of the tuple in values, and the object to convert comes after the minimum field width and optional precision. 
  14. Precision (optional), given as a "." (dot) followed by the precision. If specified as "*" (an asterisk), the actual width is read from the next element of the tuple in values, and the value to convert comes after the precision. 
  15. Length modifier (optional). 
  16. Conversion type. 
  17. When the right argument is a dictionary (or other mapping type), then the formats in the string must include a parenthesised mapping key into that dictionary inserted immediately after the "%" character. The mapping key selects the value to be formatted from the mapping. For example: 
  18.  
  19.  
  20. >>> print '%(language)s has %(#)03d quote types.' % \
  21.           {'language': "Python", "#": 2}
  22. Python has 002 quote types.
  23.  
  24. In this case no * specifiers may occur in a format (since they require a sequential parameter list). 
  25.  
  26. The conversion flag characters are: 
  27.  
  28.  
  29. Flag Meaning 
  30. # The value conversion will use the ``alternate form'' (where defined below). 
  31. 0 The conversion will be zero padded for numeric values. 
  32. - The converted value is left adjusted (overrides the "0" conversion if both are given). 
  33.   (a space) A blank should be left before a positive number (or empty string) produced by a signed conversion. 
  34. + A sign character ("+" or "-") will precede the conversion (overrides a "space" flag). 
  35.  
  36. A length modifier (h, l, or L) may be present, but is ignored as it is not necessary for Python. 
  37.  
  38. The conversion types are: 
  39.  
  40.  
  41. Conversion Meaning Notes 
  42. d Signed integer decimal.  
  43. i Signed integer decimal.  
  44. o Unsigned octal. (1) 
  45. u Unsigned decimal.  
  46. x Unsigned hexadecimal (lowercase). (2) 
  47. X Unsigned hexadecimal (uppercase). (2) 
  48. e Floating point exponential format (lowercase).  
  49. E Floating point exponential format (uppercase).  
  50. f Floating point decimal format.  
  51. F Floating point decimal format.  
  52. g Same as "e" if exponent is greater than -4 or less than precision, "f" otherwise.  
  53. G Same as "E" if exponent is greater than -4 or less than precision, "F" otherwise.  
  54. c Single character (accepts integer or single character string).  
  55. r String (converts any python object using repr()). (3) 
  56. s String (converts any python object using str()). (4) 
  57. % No argument is converted, results in a "%" character in the result.  
  58.  
  59. Notes: 
  60.  
  61. (1) 
  62. The alternate form causes a leading zero ("0") to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero. 
  63. (2) 
  64. The alternate form causes a leading '0x' or '0X' (depending on whether the "x" or "X" format was used) to be inserted between left-hand padding and the formatting of the number if the leading character of the result is not already a zero. 
  65. (3) 
  66. The %r conversion was added in Python 2.0. 
  67. (4) 
  68. If the object or format provided is a unicode string, the resulting string will also be unicode. 
  69. Since Python strings have an explicit length, %s conversions do not assume that '\0' is the end of the string. 
  70.  
  71. For safety reasons, floating point precisions are clipped to 50; %f conversions for numbers whose absolute value is over 1e25 are replaced by %g conversions.2.9 All other errors raise exceptions. 
  72.  
  73. Additional string operations are defined in standard modules string and re. 
  74.  
  75.  
Jan 24 '07 #2
dshimer
136 Expert 100+
If you are used to C/C++ you can look at it as being very similar to the formatting that goes on in the printf function. It is simply formatting. The code that goes inside the single or double quotes is almost identical to what goes inside the quotes in the printf for example
Expand|Select|Wrap|Line Numbers
  1. print "%.2lf" % (1.0/3.0)
yeilds 0.33
To get the full similarities try
Expand|Select|Wrap|Line Numbers
  1. print "When you %s %d by %d you get %.2lf" % ('divide',1,3,(1.0/3.0))
to print
When you divide 1 by 3 you get 0.33

In fact, because I started in C (though now do everything in python) one of my favorite tips from the python cookbook is to create functions that exactly mirror printf and fprint in form and function.
Only the lines that contain "lambda" are code the blocks inside the triple quotes are docstrings from my utility module.
Expand|Select|Wrap|Line Numbers
  1. printf = lambda fmt,*args: sys.stdout.write(fmt%args)
  2. '''
  3. c like implemetation of printf, for example:
  4.     printf("this is %s test with the number %.2lf",'a',9)
  5. yeilds
  6.     this is a test with the number 9.00
  7. '''
  8.  
  9. fprintf = lambda afile,fmt,*args: afile.write(fmt%args)
  10. '''
  11. Same as printf but like c's fprintf sends output to open file
  12. usage: dsutil.fprintf(AnOpenFile,"format",Values)
  13. '''
  14.  
Jan 24 '07 #3
dshimer
136 Expert 100+
Unless of course you meant to use the % as a modulo operator, in which case everything I said is off point, and the problem is syntax. The modulo is pretty well documented in it's own right.
Jan 24 '07 #4
TMS
119 100+
lol, so its a hex digit. I get it now... thank you.

About the C code and printf. I never learned C. They started me in C++ so the printf thing... well it just looks strange to me. C programmers who started with C think I'm strange, but, think about it. Its very diffierent to look at C code when not exposed to it. Only C++. I will (after I'm done with school and all the languages I'm trying to learn) go back and play with C. After all C++ shares many libraries with C, its some of the ... well, like the printf that just looks crazy.

Thank you

TMS
Jan 24 '07 #5

Sign in to post your reply or Sign up for a free account.

Similar topics

4
by: Francis Lavoie | last post by:
Hello I have some questions regarding webframework, I must say that I quite lost and these questions are basicly to help me understand the way it work. I have some knowledge with PHP and JSP....
2
by: Jo_Calico | last post by:
I love the Dynamic Drive cross browser marquee script. I'd like to make the text loop immediately after completion, so the beginning runs right after the end (does that make sense?). Could anyone...
3
by: Samuel | last post by:
I wrote a very simple httpmodule and tried to compile it with no success. This is my code: ============== Imports System Imports System.Web Imports Microsoft.VisualBasic NameSpace...
7
by: Squignibbler | last post by:
Hi all, I have a question regarding the C++ programming language regarding the nature of the relationship between pointers and arrays. If the statement MyArray is functionally identical to...
6
by: rodchar | last post by:
Hey all, I'm trying to understand Master/Detail concepts in VB.NET. If I do a data adapter fill for both customer and orders from Northwind where should that dataset live? What client is...
10
by: jojobar | last post by:
Hello, I am trying to use vs.net 2005 to migrate a project originally in vs.net 2003. I started with creation of a "web site", and then created folders for each component of the site. I read...
14
by: Mr Newbie | last post by:
I am often in the situation where I want to act on the result of a function, but a simple boolean is not enough. For example, I may have a function called isAuthorised ( User, Action ) as ?????...
2
by: Dean R. Henderson | last post by:
For an ASP.NET web application, is there a way for one session (with appropriate security authorization) to set a HttpSessionState variable to point to another session and execute the Abandon...
6
by: Jon | last post by:
All, I'm working in a fairly robust content management system for our company's websites, and have a question regarding the file and directory structure of the site. Currently, I'm populating...
5
by: archana | last post by:
Hi all, I am using timer to do some functionality on user specified time. I am using system.timers.timer class and its timer to do this functionality. What i am doing is i set autoreset to...
0
by: ryjfgjl | last post by:
In our work, we often receive Excel tables with data in the same format. If we want to analyze these data, it can be difficult to analyze them because the data is spread across multiple Excel files...
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
1
by: Sonnysonu | last post by:
This is the data of csv file 1 2 3 1 2 3 1 2 3 1 2 3 2 3 2 3 3 the lengths should be different i have to store the data by column-wise with in the specific length. suppose the i have to...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
Oralloy
by: Oralloy | last post by:
Hello folks, I am unable to find appropriate documentation on the type promotion of bit-fields when using the generalised comparison operator "<=>". The problem is that using the GNU compilers,...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...
0
agi2029
by: agi2029 | last post by:
Let's talk about the concept of autonomous AI software engineers and no-code agents. These AIs are designed to manage the entire lifecycle of a software development project—planning, coding, testing,...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.