473,581 Members | 2,786 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reverse string-formatting (maybe?)

Is there any builtin function or module with a function similar to my
made-up, not-written deformat function as follows? I can't imagine it
would be too easy to write, but possible...
>>template = 'I am %s, and he %s last %s.'
values = ('coding', "coded', 'week')
formatted = template % values
formatted
'I am coding, and he coded last week.'
>>deformat(form atted, template)
('coding', 'coded', 'week')

expanded (for better visual):
>>deformat('I am coding, and he coded last week.', 'I am %s, and he %s last %s.')
('coding', 'coded', 'week')

It would return a tuple of strings, since it has no way of telling what
the original type of each item was.
Any input? I've looked through the documentation of the string module
and re module, did a search of the documentation and a search of this
group, and come up empty-handed.

Oct 14 '06 #1
11 4988
Dustan wrote:
Is there any builtin function or module with a function similar to my
made-up, not-written deformat function as follows? I can't imagine it
would be too easy to write, but possible...
>>>template = 'I am %s, and he %s last %s.'
values = ('coding', "coded', 'week')
formatted = template % values
formatted
'I am coding, and he coded last week.'
>>>deformat(for matted, template)
('coding', 'coded', 'week')

expanded (for better visual):
>>>deformat(' I am coding, and he coded last week.', 'I am %s, and he %s
last %s.')
('coding', 'coded', 'week')

It would return a tuple of strings, since it has no way of telling what
the original type of each item was.
Any input? I've looked through the documentation of the string module
and re module, did a search of the documentation and a search of this
group, and come up empty-handed.
Simple, but unreliable:
>>import re
template = "I am %s, and he %s last %s."
values = ("coding", "coded", "week")
formatted = template % values
def deformat(format ted, template):
.... r = re.compile("(.* )".join(templat e.split("%s")))
.... return r.match(formatt ed).groups()
....
>>deformat(form atted, template)
('coding', 'coded', 'week')

Peter
Oct 14 '06 #2
>>>template = 'I am %s, and he %s last %s.'
>>>values = ('coding', "coded', 'week')
formatted = template % values
formatted
'I am coding, and he coded last week.'
>>>deformat(for matted, template)
('coding', 'coded', 'week')

expanded (for better visual):
>>>deformat(' I am coding, and he coded last week.', 'I am %s, and he %s last %s.')
('coding', 'coded', 'week')

It would return a tuple of strings, since it has no way of telling what
the original type of each item was.

Any input? I've looked through the documentation of the string module
and re module, did a search of the documentation and a search of this
group, and come up empty-handed.

Yes, in the trivial case you provide, it can be done fairly
easily using the re module:
>>import re
template = 'I am %s, and he %s last %s.'
values = ('coding', 'coded', 'week')
formatted = template % values
unformat_re = re.escape(templ ate).replace('% s', '(.*)')
# unformat_re = unformat_re.rep lace('%i', '([0-9]+)')
r = re.compile(unfo rmat_re)
r.match(forma tted).groups()
('coding', 'coded', 'week')

Thing's get crazier when you have things like
>>answer ='format values into a string'
template = 'The formatting string %%s is used to %s' % answer
or
>>template = 'The value is %0*.*f'
values = (10, 4, 3.14159)
formatted = template % values
formated
'The value is 00003.1415'

or
>>template = 'Dear %(name)s, Thank you for the %(gift)s. It
was very %(adj).' % {'name': 'Grandma', 'gift': 'sweater', 'adj':
'nice'}

Additionally, things go a little tangled when the replacement
values duplicate matters in the template. Should the unformatting
of "I am tired, and he didn't last last All Saint's Day" be
parsed as ('tired', "didn't last", "All Saint's Day") or
('tired', "didn't", "last All Saint's Day"). The /intent/ is
likely the former, but getting a computer to understand intent is
a non-trivial task ;)

Just a few early-morning thoughts...

-tkc


Oct 14 '06 #3
>>>template = 'I am %s, and he %s last %s.'
>>>values = ('coding', "coded', 'week')
formatted = template % values
formatted
'I am coding, and he coded last week.'
>>>deformat(for matted, template)
('coding', 'coded', 'week')

expanded (for better visual):
>>>deformat(' I am coding, and he coded last week.', 'I am %s, and he %s last %s.')
('coding', 'coded', 'week')

It would return a tuple of strings, since it has no way of telling what
the original type of each item was.

Any input? I've looked through the documentation of the string module
and re module, did a search of the documentation and a search of this
group, and come up empty-handed.

Yes, in the trivial case you provide, it can be done fairly
easily using the re module:
>>import re
template = 'I am %s, and he %s last %s.'
values = ('coding', 'coded', 'week')
formatted = template % values
unformat_re = re.escape(templ ate).replace('% s', '(.*)')
# unformat_re = unformat_re.rep lace('%i', '([0-9]+)')
r = re.compile(unfo rmat_re)
r.match(forma tted).groups()
('coding', 'coded', 'week')

Thing's get crazier when you have things like
>>answer ='format values into a string'
template = 'The formatting string %%s is used to %s' % answer
or
>>template = 'The value is %0*.*f'
values = (10, 4, 3.14159)
formatted = template % values
formated
'The value is 00003.1415'

or
>>template = 'Dear %(name)s, Thank you for the %(gift)s. It
was very %(adj).' % {'name': 'Grandma', 'gift': 'sweater', 'adj':
'nice'}

Additionally, things go a little tangled when the replacement
values duplicate matters in the template. Should the unformatting
of "I am tired, and he didn't last last All Saint's Day" be
parsed as ('tired', "didn't last", "All Saint's Day") or
('tired', "didn't", "last All Saint's Day"). The /intent/ is
likely the former, but getting a computer to understand intent is
a non-trivial task ;)

Just a few early-morning thoughts...

-tkc


Oct 14 '06 #4

Peter Otten wrote:
Dustan wrote:
Is there any builtin function or module with a function similar to my
made-up, not-written deformat function as follows? I can't imagine it
would be too easy to write, but possible...
>>template = 'I am %s, and he %s last %s.'
values = ('coding', "coded', 'week')
formatted = template % values
formatted
'I am coding, and he coded last week.'
>>deformat(form atted, template)
('coding', 'coded', 'week')

expanded (for better visual):
>>deformat('I am coding, and he coded last week.', 'I am %s, and he %s
last %s.')
('coding', 'coded', 'week')

It would return a tuple of strings, since it has no way of telling what
the original type of each item was.
Any input? I've looked through the documentation of the string module
and re module, did a search of the documentation and a search of this
group, and come up empty-handed.

Simple, but unreliable:
>import re
template = "I am %s, and he %s last %s."
values = ("coding", "coded", "week")
formatted = template % values
def deformat(format ted, template):
... r = re.compile("(.* )".join(templat e.split("%s")))
... return r.match(formatt ed).groups()
...
>deformat(forma tted, template)
('coding', 'coded', 'week')

Peter
Trying to figure out the 'unreliable' part of your statement...

I'm sure 2 '%s' characters in a row would be a bad idea, and if you
have similar expressions for the '%s' characters within as well as in
the neighborhood of the '%s', that would cause difficulty. Is there any
other reason it might not work properly?

My template outside of the '%s' characters contains only commas and
spaces, and within, neither commas nor spaces. Given that information,
is there any reason it might not work properly?

Oct 15 '06 #5
My template outside of the '%s' characters contains only commas and
spaces, and within, neither commas nor spaces. Given that information,
is there any reason it might not work properly?
Given this new (key) information along with the assumption that
you're doing straight string replacement (not dictionary
replacement of the form "%(key)s" or other non-string types such
as "%05.2f"), then yes, a reversal is possible. To make it more
explicit, one would do something like
>>template = '%s, %s, %s'
values = ('Tom', 'Dick', 'Harry')
formatted = template % values
import re
unformat_stri ng = template.replac e('%s', '([^, ]+)')
unformatter = re.compile(unfo rmat_string)
extracted_val ues = unformatter.sea rch(formatted). groups()
using '[^, ]+' to mean "one or more characters that aren't a
comma or a space".

-tkc


Oct 15 '06 #6

Tim Chase wrote:
My template outside of the '%s' characters contains only commas and
spaces, and within, neither commas nor spaces. Given that information,
is there any reason it might not work properly?

Given this new (key) information along with the assumption that
you're doing straight string replacement (not dictionary
replacement of the form "%(key)s" or other non-string types such
as "%05.2f"), then yes, a reversal is possible. To make it more
explicit, one would do something like
>>template = '%s, %s, %s'
>>values = ('Tom', 'Dick', 'Harry')
>>formatted = template % values
>>import re
>>unformat_stri ng = template.replac e('%s', '([^, ]+)')
>>unformatter = re.compile(unfo rmat_string)
>>extracted_val ues = unformatter.sea rch(formatted). groups()

using '[^, ]+' to mean "one or more characters that aren't a
comma or a space".

-tkc
Thanks.

One more thing (I forgot to mention this other situation earlier)
The %s characters are ints, and outside can be anything except int
characters. I do have one situation of '%s%s%s', but I can change it to
'%s', and change the output into the needed output, so that's not
important. Think something along the lines of "abckdaldj iweo%s
qwierxcnv !%sjd".

Oct 15 '06 #7

Dustan wrote:
Tim Chase wrote:
My template outside of the '%s' characters contains only commas and
spaces, and within, neither commas nor spaces. Given that information,
is there any reason it might not work properly?
Given this new (key) information along with the assumption that
you're doing straight string replacement (not dictionary
replacement of the form "%(key)s" or other non-string types such
as "%05.2f"), then yes, a reversal is possible. To make it more
explicit, one would do something like
>>template = '%s, %s, %s'
>>values = ('Tom', 'Dick', 'Harry')
>>formatted = template % values
>>import re
>>unformat_stri ng = template.replac e('%s', '([^, ]+)')
>>unformatter = re.compile(unfo rmat_string)
>>extracted_val ues = unformatter.sea rch(formatted). groups()
using '[^, ]+' to mean "one or more characters that aren't a
comma or a space".

-tkc

Thanks.

One more thing (I forgot to mention this other situation earlier)
The %s characters are ints, and outside can be anything except int
characters. I do have one situation of '%s%s%s', but I can change it to
'%s', and change the output into the needed output, so that's not
important. Think something along the lines of "abckdaldj iweo%s
qwierxcnv !%sjd".
That was written in haste. All the information is true. The question:
I've already created a function to do this, using your original
deformat function. Is there any way in which it might go wrong?

Oct 15 '06 #8

Dustan wrote:
Dustan wrote:
Tim Chase wrote:
My template outside of the '%s' characters contains only commas and
spaces, and within, neither commas nor spaces. Given that information,
is there any reason it might not work properly?
>
Given this new (key) information along with the assumption that
you're doing straight string replacement (not dictionary
replacement of the form "%(key)s" or other non-string types such
as "%05.2f"), then yes, a reversal is possible. To make it more
explicit, one would do something like
>
>>template = '%s, %s, %s'
>>values = ('Tom', 'Dick', 'Harry')
>>formatted = template % values
>>import re
>>unformat_stri ng = template.replac e('%s', '([^, ]+)')
>>unformatter = re.compile(unfo rmat_string)
>>extracted_val ues = unformatter.sea rch(formatted). groups()
>
using '[^, ]+' to mean "one or more characters that aren't a
comma or a space".
>
-tkc
Thanks.

One more thing (I forgot to mention this other situation earlier)
The %s characters are ints, and outside can be anything except int
characters. I do have one situation of '%s%s%s', but I can change it to
'%s', and change the output into the needed output, so that's not
important. Think something along the lines of "abckdaldj iweo%s
qwierxcnv !%sjd".

That was written in haste. All the information is true. The question:
I've already created a function to do this, using your original
deformat function. Is there any way in which it might go wrong?
Again, haste. I used Peter's deformat function.

Oct 15 '06 #9
On 14 Oct 2006 05:35:02 -0700,
"Dustan" <Du**********@g mail.comwrote:
Is there any builtin function or module with a function similar to my
made-up, not-written deformat function as follows? I can't imagine it
would be too easy to write, but possible...
[ snip ]
Any input? I've looked through the documentation of the string module
and re module, did a search of the documentation and a search of this
group, and come up empty-handed.
Track down pyscanf. (Google is your friend, but I can't find any sort
of licensing/copyright information, and the web addresses in the source
code aren't available, so I hesitate to post my ancient copy.)

HTH,
Dan

--
Dan Sommers
<http://www.tombstoneze ro.net/dan/>
"I wish people would die in alphabetical order." -- My wife, the genealogist
Oct 15 '06 #10

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

Similar topics

5
3009
by: Thomas Philips | last post by:
Consider the following simple dictionary e={1:'one', 2: 'two'} e >>>'one' However, If I attempt to print e using a formatted string print " %(1)s" %e, I get a KeyError: '1'
20
3281
by: Pierre Fortin | last post by:
Hi! "Python Essential Reference" - 2nd Ed, on P. 47 states that a string format can include "*" for a field width (no restrictions noted); yet... >>> "%*d" % (6,2) # works as expected ' 2' Now, with a mapping....
5
1612
by: rodney.maxwell | last post by:
Was doing some string formatting, noticed the following: >>> x = None >>> "%s" % x 'None' Is there a reason it maps to 'None'? I had expected ''.
0
1476
by: David Rifkind | last post by:
I've seen some strange string formatting behavior on several XP and 2000 machines. I can get the same results with Graphics.DrawString, but the easiest way to see it is to put a label on a VB or C# form, leave the label's font setting at the default, set AutoSize to true, and set the text property to a long string of narrow characters, like:...
0
1172
by: Top Gun | last post by:
I have been finding difficulty in locating decent, in-depth information on a standard matter in the IT world... STRING FORMATTING. Particuarlly as it relates to C# (or .NET). The books I have give little attention to this basic need. Parsing, replacing, splitting, finding substrings, etc. doesn't seem to be highlighted or easily searched...
3
1648
by: Franck | last post by:
hello, i'm looking for code (C# preferably) in order to change programmatically in a datagrid the string formatting expression of one bound colum thank you
7
1684
by: Steven D'Aprano | last post by:
I have a sinking feeling I'm missing something really, really simple. I'm looking for a format string similar to '%.3f' except that trailing zeroes are not included. To give some examples: Float String 1.0 1
27
2809
by: fdu.xiaojf | last post by:
Hi, String formatting can be used to converting an integer to its octal or hexadecimal form: '307' 'c7' But, can string formatting be used to convert an integer to its binary form ?
7
17066
by: sherifffruitfly | last post by:
Hi, God I hate datetime string formatting... How do I get a string of the form "04-Oct-2006", for example, from a DateTime object? Thanks a jillion, cdj
2
1798
by: Tim Chase | last post by:
Is there an easy way to make string-formatting smart enough to gracefully handle iterators/generators? E.g. transform = lambda s: s.upper() pair = ('hello', 'world') print "%s, %s" % pair # works print "%s, %s" % map(transform, pair) # fails with a """ TypeError: not enough arguments for format string
0
7882
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...
0
7808
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...
0
8157
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. ...
1
7914
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...
0
8181
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...
0
3809
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...
0
3835
by: adsilva | last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
1
1410
muto222
by: muto222 | last post by:
How can i add a mobile payment intergratation into php mysql website.
0
1145
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...

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.