473,790 Members | 3,083 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Converting a string to the most probable type

Hi,

I would like to know if there is a module that converts a string to a
value of the "most probable type" ; for instance :
- if the string is "abcd" the value is the same string "abcd"
- string "123" : value = the integer 123
- string "-1.23" (or "-1,23" if the locale for decimals is ,) : value
= the float -1.23
- string "2008/03/06" (the format is also locale-dependant) : value =
datetime.date(2 008,03,06)

Like in spreadsheets, special prefixes could be used to force the
type : for instance '123 would be converted to the *string* "123"
instead of the *integer* 123

I could code it myself, but this wheel is probably already invented

Regards,
Pierre
Mar 6 '08 #1
13 1783
On Mar 6, 9:27 am, Pierre Quentel <quentel.pie... @wanadoo.frwrot e:
Hi,

I would like to know if there is a module that converts a string to a
value of the "most probable type" ; for instance :
- if the string is "abcd" the value is the same string "abcd"
- string "123" : value = the integer 123
- string "-1.23" (or "-1,23" if the locale for decimals is ,) : value
= the float -1.23
- string "2008/03/06" (the format is also locale-dependant) : value =
datetime.date(2 008,03,06)

Like in spreadsheets, special prefixes could be used to force the
type : for instance '123 would be converted to the *string* "123"
instead of the *integer* 123

I could code it myself, but this wheel is probably already invented
Maybe, but that's a so domain-specific and easy to code wheel that
it's no big deal reinventing.

George
Mar 6 '08 #2
On Mar 6, 3:20*pm, George Sakkis <george.sak...@ gmail.comwrote:
On Mar 6, 9:27 am, Pierre Quentel <quentel.pie... @wanadoo.frwrot e:


Hi,
I would like to know if there is a module that converts a string to a
value of the "most probable type" ; for instance :
- if the string is "abcd" the value is the same string "abcd"
- string "123" : value = the integer 123
- string "-1.23" (or "-1,23" if the locale for decimals is ,) : value
= the float -1.23
- string "2008/03/06" (the format is also locale-dependant) : value =
datetime.date(2 008,03,06)
Like in spreadsheets, special prefixes could be used to force the
type : for instance '123 would be converted to the *string* "123"
instead of the *integer* 123
I could code it myself, but this wheel is probably already invented

Maybe, but that's a so domain-specific and easy to code wheel that
it's no big deal reinventing.

George- Hide quoted text -

- Show quoted text -
Actually you could probably write your own code very easily, a couple
of try/except clauses. I would recommend you try int() first, then
try float(), then try date check and when all else fails leave it a
string. However, it may be an interesting challenge for those who are
willing to make the attempt. "Define Cell/Field contents".
Mar 6 '08 #3
On 6 mar, 11:27, Pierre Quentel <quentel.pie... @wanadoo.frwrot e:
Hi,

I would like to know if there is a module that converts a string to a
value of the "most probable type" ; for instance :
- if the string is "abcd" the value is the same string "abcd"
- string "123" : value = the integer 123
- string "-1.23" (or "-1,23" if the locale for decimals is ,) : value
= the float -1.23
- string "2008/03/06" (the format is also locale-dependant) : value =
datetime.date(2 008,03,06)

Like in spreadsheets, special prefixes could be used to force the
type : for instance '123 would be converted to the *string* "123"
instead of the *integer* 123

I could code it myself, but this wheel is probably already invented

Regards,
Pierre
>>def convert(x):
if '.' in x:
try: return float(x)
except ValueError: return x
else:
try: return int(x)
except: return x

>>convert('123' )
123
>>convert('123. 99')
123.98999999999 999
>>convert('hell o')
'hello'
Mar 6 '08 #4
On Mar 6, 9:17 pm, Luis M. González <luis...@gmail. comwrote:
On 6 mar, 11:27, Pierre Quentel <quentel.pie... @wanadoo.frwrot e:
Hi,
I would like to know if there is a module that converts a string to a
value of the "most probable type" ; for instance :
- if the string is "abcd" the value is the same string "abcd"
- string "123" : value = the integer 123
- string "-1.23" (or "-1,23" if the locale for decimals is ,) : value
= the float -1.23
- string "2008/03/06" (the format is also locale-dependant) : value =
datetime.date(2 008,03,06)
Like in spreadsheets, special prefixes could be used to force the
type : for instance '123 would be converted to the *string* "123"
instead of the *integer* 123
I could code it myself, but this wheel is probably already invented
Regards,
Pierre
>def convert(x):

if '.' in x:
try: return float(x)
except ValueError: return x
else:
try: return int(x)
except: return x
>convert('123 ')
123
>convert('123.9 9')
123.98999999999 999
>convert('hello ')

'hello'
Neat solution. The real challenge though is whether to support
localised dates, these are all valid:
20/10/01
102001
20-10-2001
20011020
Mar 7 '08 #5
And so on and so forth. *The tricky bit is how to tell the difference
between Day, Month and Year.
There isn't one.
Mar 7 '08 #6
Pierre Quentel <qu************ @wanadoo.frwrit es:
I would like to know if there is a module that converts a string to a
value of the "most probable type"
Python 2.4.4 (#1, Oct 23 2006, 13:58:00)
>>import this
The Zen of Python, by Tim Peters
...
In the face of ambiguity, refuse the temptation to guess.
Mar 8 '08 #7
On Mar 8, 11:13 am, Paul Rubin <http://phr...@NOSPAM.i nvalidwrote:
Pierre Quentel <quentel.pie... @wanadoo.frwrit es:
I would like to know if there is a module that converts a string to a
value of the "most probable type"

Python 2.4.4 (#1, Oct 23 2006, 13:58:00)
>>import this
The Zen of Python, by Tim Peters
...
In the face of ambiguity, refuse the temptation to guess.
Reminds me of the story about the avionics software for a fighter
plane which when faced with the situation of being exactly upside-down
refused to guess whether it should initiate a left roll or a right
roll :-)
Mar 8 '08 #8
On Fri, 07 Mar 2008 16:13:04 -0800, Paul Rubin wrote:
Pierre Quentel <qu************ @wanadoo.frwrit es:
>I would like to know if there is a module that converts a string to a
value of the "most probable type"

Python 2.4.4 (#1, Oct 23 2006, 13:58:00)
>>import this
The Zen of Python, by Tim Peters
...
In the face of ambiguity, refuse the temptation to guess.
Good advice, but one which really only applies to libraries. At the
application level, sometimes (but not always, or even most times!)
guessing is the right thing to do.

E.g. spreadsheet applications don't insist on different syntax for
strings, dates and numbers. You can use syntax to force one or the other,
but by default the application will auto-detect what you want according
to relatively simple, predictable and intuitive rules:

* if the string looks like a date, it's a date;
* if it looks like a number, it's a number;
* otherwise it's a string.

Given the user-base of the application, the consequences of a wrong
guess, and the ease of fixing it, guessing is the right thing to do.

Auto-completion is another good example of guessing in the face of
ambiguity. It's not guessing that is bad, but what you do with the guess.
--
Steven
Mar 8 '08 #9
>def convert(x):
>
* * * * if '.' in x:
* * * * * * * * try: return float(x)
* * * * * * * * except ValueError: return x
* * * * else:
* * * * * * * * try: return int(x)
* * * * * * * * except: return x
>convert('123 ')
123
>convert('123.9 9')
123.98999999999 999
>convert('hello ')
Hi,

That's fine for people who write floats with a "." ; but others learn
to enter them with ","

For the same float, the French write the literal 123.456.789,99 when
others write 123,456,789.99 ; for us, today is 8/3/2008 (or
08/03/2008) where for others it's 3/8/2008 or perhaps 2008/3/8

Popular spreadsheets know how to "guess" literals ; if the guess is
not correct users can usually specify the pattern to use. My question
was just to know if something similar had already been developed in
Python ; I understand that the answer is no

Thanks,
Pierre
Mar 8 '08 #10

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

Similar topics

5
13928
by: matt melton | last post by:
Hi there, I am trying to write a method that accepts an array of any primitive type and will return the same array without copying memory as an array of bytes. ie. I'd like to be able to do something like: char chars = "Hello!"; byte bytes = (byte) chars;
19
6166
by: Erik Wikström | last post by:
First of all, forgive me if this is the wrong place to ask this question, if it's a stupid question (it's my second week with C++), or if this is answered some place else (I've searched but not found anything). Here's the problem, I have two sets of files, the name of a file contains a number which is unique for each set but it's possible (even probable) that two files in different sets have the same numbers. I want to store these...
45
5324
by: Rakesh | last post by:
Hi, I have this function to reverse the given string. I am just curious if that is correct and there could be better way of doing it / probable bugs in the same. The function prototype is similar to the one in any standard C library. <---- Code starts -->
2
5753
by: Asbjørn Ulsberg | last post by:
Hi. I'm trying to convert Brady Hegberg's great RTF2HTML VB 6.0 module to C#. I've managed to convert the VB code to VB.NET, which gave me the following code: Option Strict On Option Explicit On Option Compare Binary
21
8366
by: oksuresh | last post by:
Hi talents, I have noticed that atof() function approximates the string I pass to it. when I use atof() , as atof(" 184.64") and it returns 184.63999999999 But I would like to have the exact value that is passed.
9
2579
by: Terry | last post by:
I am converting (attempting) some vb6 code that makes vast use of interfaces. One of the major uses is to be able to split out Read-only access to an obect. Let me give you a simple (contrived) example: In Project RoObjDefs: RoPerson.cls file: Public Property Get FirstName() as String Public Property Get LastName() as String <end of file RoPerson.cls> RoPersons.cls file Public Function Count() as Integer
2
4010
by: CoreyWhite | last post by:
Problem: You have numbers in string format, but you need to convert them to a numeric type, such as an int or float. Solution: You can do this with the standard library functions. The functions strtol, strtod, and strtoul, defined in <cstdlib>, convert a null- terminated character string to a long int, double, or unsigned long. You can use them to convert numeric strings of any base to a numeric
2
11185
by: Brian Parker | last post by:
I am beginning to work with VB2005.NET and I'm getting some problems with string formatting converting an application from VB6. VB6 code:- sTradeDate = Format(pArray(4,i Record), "mmddyy") pArray is a variant array containing a date string at pArray(4, iRecord) in the format "yyyy/mm/dd"
3
1818
by: Dhananjay | last post by:
Hi All, I am facing problem when i am converting C#.net code(Delegate concept) into vb.net. I am unable to do that . Can someone help me to solve the problem. I am providing my C#.net code. ==================================my code is :- ====================================== static public List<MembershipUserWrapperGetMembers(bool
0
9666
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
9512
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
10201
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 tapestry of website design and digital marketing. It's not merely about having a website; it's about crafting an immersive digital experience that captivates audiences and drives business growth. The Art of Business Website Design Your website is...
1
10147
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
9987
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...
1
7531
isladogs
by: isladogs | last post by:
The next Access Europe User Group meeting will be on Wednesday 1 May 2024 starting at 18:00 UK time (6PM UTC+1) and finishing by 19:30 (7.30PM). In this session, we are pleased to welcome a new presenter, Adolph Dupré who will be discussing some powerful techniques for using class modules. He will explain when you may want to use classes instead of User Defined Types (UDT). For example, to manage the data in unbound forms. Adolph will...
0
6770
by: conductexam | last post by:
I have .net C# application in which I am extracting data from word file and save it in database particularly. To store word all data as it is I am converting the whole word file firstly in HTML and then checking html paragraph one by one. At the time of converting from word file to html my equations which are in the word document file was convert into image. Globals.ThisAddIn.Application.ActiveDocument.Select();...
1
4100
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
3
2910
bsmnconsultancy
by: bsmnconsultancy | last post by:
In today's digital era, a well-designed website is crucial for businesses looking to succeed. Whether you're a small business owner or a large corporation in Toronto, having a strong online presence can significantly impact your brand's success. BSMN Consultancy, a leader in Website Development in Toronto offers valuable insights into creating effective websites that not only look great but also perform exceptionally well. In this comprehensive...

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.