473,668 Members | 2,799 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

In a dynamic language, why % operator asks user for type info?

Hi,

The string format operator, %, provides a functionality similar to the
snprintf function in C. In C, the function does not know the type of
each of the argument and hence relies on the embedded %<char>
specifier to guide itself while retrieving args.

In python, the language already provides ways to know the type of an
object.

So in

output = '%d foo %d bar" % (foo_count, bar_count),
why we need to use %d? I'm thinking some general common placeholder,
say %x (currently it's hex..) could be used.

output = '%x foo %x bar" % (foo_count, bar_count).
Since % by definition is string formatting, the operator should be
able to infer how to convert each of the argument into strings.

If the above is the case, we could've avoided all those exceptions
that happen when a %d is specified but say a string is passed.

Thanks,
Karthik

Jul 17 '07 #1
9 1050
On Jul 16, 7:10 pm, Karthik Gurusamy <kar1...@gmail. comwrote:
Hi,

The string format operator, %, provides a functionality similar to the
snprintf function in C. In C, the function does not know the type of
each of the argument and hence relies on the embedded %<char>
specifier to guide itself while retrieving args.

In python, the language already provides ways to know the type of an
object.

So in

output = '%d foo %d bar" % (foo_count, bar_count),
why we need to use %d? I'm thinking some general common placeholder,
say %x (currently it's hex..) could be used.

output = '%x foo %x bar" % (foo_count, bar_count).
Since % by definition is string formatting, the operator should be
able to infer how to convert each of the argument into strings.
You want all your numbers to print in hexadecimal?
>
If the above is the case, we could've avoided all those exceptions
that happen when a %d is specified but say a string is passed.
Who does that?
>
Thanks,
Karthik

Jul 17 '07 #2
I don't have a good answer for you, but you might be interested to
read this: http://python.org/dev/peps/pep-3101/. Which according to a
recent blog post by BDFL is going to be how string formatting is done
in Python3000.

The character doesn't specify the type to expect, but the formatting
function. So, %s calls a string formatter, %r calls repr and %x calls
a hex formatter. The there may be multiple formatters that produce
different results for given types. An integer can use %d,%e,%f,%s,%x
or %r, and they all produce slightly different results. Also, the
formatters take parameters. Such as "%+010.5f"%(1.2 3) which produces
"+001.23000 ".
Jul 17 '07 #3
On Mon, 2007-07-16 at 17:33 -0700, Karthik Gurusamy wrote:
Thanks. The above surprised me as I didn't expect that %s will accept
42.

Looks like the implicit conversion doesn't work the other way.
>'%s' % 42
'42'
>'%d' % '42'
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: int argument required
>>

Looks like %s can be used even when I'm sending non-strings.
>'%s foo %s bar' % (25, 25.34)
'25 foo 25.34 bar'
>>

So %s seems to serve the multi-type placeholder.
According to the docs: http://docs.python.org/lib/typesseq-strings.html

By design, %s "converts any python object using str()". OTOH it does
not specify that %d, for example, calls int().
Jul 17 '07 #4
On Jul 16, 8:10 pm, Karthik Gurusamy <kar1...@gmail. comwrote:
Since % by definition is string formatting, the operator should be
able to infer how to convert each of the argument into strings.
In addition to what Dan mentioned, you can use "%s" with any object to
perform an automatic string conversion.
>>'%s %s %s %s' % ('Hello!', 3.14, 42+1j, object())
'Hello! 3.14 (42+1j) <object object at 0x41448>'

-Miles

Jul 17 '07 #5
On Jul 17, 3:10 am, Karthik Gurusamy <kar1...@gmail. comwrote:
output = '%d foo %d bar" % (foo_count, bar_count),
why we need to use %d? I'm thinking some general common placeholder,
say %x (currently it's hex..) could be used.
You already answered it in the parenthesized remark: the %d
placeholder is not only type bound but provides an additonal
distinction e.g. the one between decimals and hexadecimals. The kind
of general placeholder you want %x being requested for is actually %s
which formats decimals quite well unless you want leading zeros.

Jul 17 '07 #6
On Jul 17, 1:10 am, Karthik Gurusamy <kar1...@gmail. comwrote:
Hi,

The string format operator, %, provides a functionality similar to the
snprintf function in C. In C, the function does not know the type of
each of the argument and hence relies on the embedded %<char>
specifier to guide itself while retrieving args.

In python, the language already provides ways to know the type of an
object.

So in

output = '%d foo %d bar" % (foo_count, bar_count),
why we need to use %d? I'm thinking some general common placeholder,
say %x (currently it's hex..) could be used.

output = '%x foo %x bar" % (foo_count, bar_count).
Since % by definition is string formatting, the operator should be
able to infer how to convert each of the argument into strings.

If the above is the case, we could've avoided all those exceptions
that happen when a %d is specified but say a string is passed.

Thanks,
Karthik
'%s' might be what your after as a more 'general purpose' moifier.

- Paddy.

Jul 17 '07 #7
marduk <ma****@nbk.hop to.orgwrote:
By design, %s "converts any python object using str()". OTOH it does
not specify that %d, for example, calls int().
No, but it does say that the 'd' is a conversion type meaning 'signed
integer decimal', and indeed anything which has an __int__ method may be
passed to the %d formatter:
>>class C:
def __int__(self):
return 42

>>"%d" % C()
'42'
>>"%d" % 3.5
'3'
Jul 17 '07 #8
On Jul 17, 2:19 am, Paddy <paddy3...@goog lemail.comwrote :
On Jul 17, 1:10 am, Karthik Gurusamy <kar1...@gmail. comwrote:


Hi,
The string format operator, %, provides a functionality similar to the
snprintf function in C. In C, the function does not know the type of
each of the argument and hence relies on the embedded %<char>
specifier to guide itself while retrieving args.
In python, the language already provides ways to know the type of an
object.
So in
output = '%d foo %d bar" % (foo_count, bar_count),
why we need to use %d? I'm thinking some general common placeholder,
say %x (currently it's hex..) could be used.
output = '%x foo %x bar" % (foo_count, bar_count).
Since % by definition is string formatting, the operator should be
able to infer how to convert each of the argument into strings.
If the above is the case, we could've avoided all those exceptions
that happen when a %d is specified but say a string is passed.
Thanks,
Karthik

'%s' might be what your after as a more 'general purpose' moifier.

- Paddy.- Hide quoted text -

- Show quoted text -
It is good for that; I generally use %s until I decide that something
needs picky formatting.

--
a = '%s Weaver' % random.choice(['Lani','Star',' Azure'])
a += 'is strange.'

Jul 17 '07 #9
On Jul 17, 5:38 pm, Duncan Booth <duncan.bo...@i nvalid.invalidw rote:
indeed anything which has an __int__ method may be
passed to the %d formatter:
Anything?! Sorry to be persnickety here, but what about this:

class C :
def __int__ (self) : pass

'%d' % C()

or this:

def foo (val) : return val
foo.__int__ = lambda x=42 : int(x)

'%d' % foo('spam')

OK, they can be passed ...

Jul 18 '07 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

3
1312
by: Stephen Gennard | last post by:
Hello, I having a problem dynamically invoking a static method that takes a reference to a SByte*. If I do it directly it works just fine. Anyone any ideas why? I have include a example below... --
3
11222
by: sferriol | last post by:
hello is it possible with postgres 7.2 or more, to define a dynamic view. For example, i have a table with a column 'user' and i want to define a view which gives infomrations from different tables but the user has to specifie the 'user' parameter when using a select to the view sylvain
7
3383
by: serge | last post by:
How can I run a single SP by asking multiple sales question either by using the logical operator AND for all the questions; or using the logical operator OR for all the questions. So it's always either AND or OR but never mixed together. We can use Northwind database for my question, it is very similar to the structure of the problem on the database I am working on. IF(SELECT OBJECT_ID('REPORT')) IS NOT NULL DROP TABLE REPORT_SELECTION
15
2312
by: Kapil Jain | last post by:
Dear All, What i need to achieve is : I am generating dynamic text boxes thru dhtml coding, i need onChange event of oragnistation text box i.e dynamically generated on click of "More" button in myhtml page in series manner like oragnisation0,oragnisation1,oragnisation2 and so on, and popup window will open onChange event of (oraganisation<iCount>) with one query string / parameter i.e value of oraganisation so that i will use that...
10
4909
by: jflash | last post by:
Hello all, I feel dumb having to ask this question in the first place, but I just can not figure it out. I am wanting to set my site up using dynamic urls (I'm assuming that's what they're called, an example of what I have in mind is index.php?page=). However, I can not figure out how to do this. I will eventually want to use SEF urls, but for now I'll be content just to have the dynamic urls. If anyone can tell me how to do this, I'd...
23
7397
by: sandy | last post by:
I need (okay, I want) to make a dynamic array of my class 'Directory', within my class Directory (Can you already smell disaster?) Each Directory can have subdirectories so I thought to put these in an array. The application compiles but aborts without giving me any useful information. What I suspect is happening is infinite recursion. Each Directory object creates an array of Subdirectories each of which has an array of...
26
2799
by: Jerim79 | last post by:
I need to create a form that takes a number that the user enters, and duplicates a question the number of times the user entered. For instance, if the customer enters 5 on the first page, when they press next the form generates "How old are you?" 5 times on the page. The customer will answer all 5 questions then press next. Finally, all the local variables get dynamically created and written to a database. I have already taken care of...
5
2580
by: bearophileHUGS | last post by:
I often use Python to write small programs, in the range of 50-500 lines of code. For example to process some bioinformatics data, perform some data munging, to apply a randomized optimization algorithm to solve a certain messy problem, and many different things. For that I often use several general modules that I have written, like implementation of certain data structures, and small general "utility" functions/classes, plus of course...
1
4504
by: remya1000 | last post by:
i'm using VB.net 2003 application program. i'm trying to convert a VB6 program to VB.NET. The VB6 code i'm trying to convert is shown below. declared g_Share() array in module and trying to add values to it inside form. VB6 (Code inside Module) 'Global type array to hold printer info. Public Type OShare PrinterName As String
0
8462
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, people are often confused as to whether an ONU can Work As a Router. In this blog post, we’ll explore What is ONU, What Is Router, ONU & Router’s main usage, and What is the difference between ONU and Router. Let’s take a closer look ! Part I. Meaning of...
0
8381
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can effortlessly switch the default language on Windows 10 without reinstalling. I'll walk you through it. First, let's disable language synchronization. With a Microsoft account, language settings sync across devices. To prevent any complications,...
0
8893
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, it seems that the internal comparison operator "<=>" tries to promote arguments from unsigned to signed. This is as boiled down as I can make it. Here is my compilation command: g++-12 -std=c++20 -Wnarrowing bit_field.cpp Here is the code in...
1
8583
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 Update option using the Control Panel or Settings app; it automatically checks for updates and installs any it finds, whether you like it or not. For most users, this new feature is actually very convenient. If you want to control the update process,...
0
8656
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 protocol has its own unique characteristics and advantages, but as a user who is planning to build a smart home system, I am a bit confused by the choice of these technologies. I'm particularly interested in Zigbee because I've heard it does some...
0
4205
by: TSSRALBI | last post by:
Hello I'm a network technician in training and I need your help. I am currently learning how to create and manage the different types of VPNs and I have a question about LAN-to-LAN VPNs. The last exercise I practiced was to create a LAN-to-LAN VPN between two Pfsense firewalls, by using IPSEC protocols. I succeeded, with both firewalls in the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
0
4380
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
2791
by: 6302768590 | last post by:
Hai team i want code for transfer the data from one system to another through IP address by using C# our system has to for every 5mins then we have to update the data what the data is updated we have to send another system
2
2023
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.

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.