473,387 Members | 1,812 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,387 software developers and data experts.

Python String Substitution

In Python, dictionaries can have any hashable value as a string. In
particular I can say

d = {}
d[(1,2)] = "Right"
d["(1,2)"] = "Wrong"
d["key"] = "test"

In order to print "test" using % substitution I can say

print "%(key)s" % d

Is there a way to print "Right" using % substitution?

print "%((1,2))s" % d

gives me "Wrong". Is there any syntax which will allow me to get
"Right" using % substitution?

- Murali

Jan 26 '06 #1
5 4392
On Thu, 26 Jan 2006 15:40:47 -0800, Murali wrote:
In Python, dictionaries can have any hashable value as a string.
No. Dictionaries can have any hashable value as a KEY. They are not
automatically converted to strings.
In particular I can say

d = {}
d[(1,2)] = "Right"
d["(1,2)"] = "Wrong"
d["key"] = "test"

In order to print "test" using % substitution I can say

print "%(key)s" % d
Yes, because the dictionary has a key which is the string "key".
Is there a way to print "Right" using % substitution?
print "%s" % "Right"
print "%s" % d[(1,2)]
print "%s%s" % ("R", "ight")

and so on.
print "%((1,2))s" % d

gives me "Wrong".
Yes, because the dictionary has a key which is the string "(1,2)".

Is there any syntax which will allow me to get "Right" using %
substitution?


You need to change your strategy. The dictionary form of string
substitution only works with keys which are strings. Look at it this way:

print "something %(x)s something" % somedict

"something %(x)s something" is a string, so all the substrings of it are
also strings, including "x". That's pretty obvious. But the same holds if
you change the x to something else:

print "something %(123.456)s something" % somedict

"123.456" is still a string.
--
Steven.

Jan 27 '06 #2

"Murali" <ma*********@gmail.com> wrote in message
news:11*********************@z14g2000cwz.googlegro ups.com...
In Python, dictionaries can have any hashable value as a string. In
particular I can say

d = {}
d[(1,2)] = "Right"
d["(1,2)"] = "Wrong"
d["key"] = "test"

In order to print "test" using % substitution I can say

print "%(key)s" % d

Is there a way to print "Right" using % substitution?

print "%((1,2))s" % d

gives me "Wrong". Is there any syntax which will allow me to get
"Right" using % substitution?

One way would be to make an adapter to convert that string to a tuple:
class adapter:
def __init__(self, dc):
self.dc = dc
def __getitem__(self,item):
return self.dc[eval(item)]

Then you could use this as:
print "%((1,2))s" % adapter(d)

I wouldn't actually recommend using eval in production code, due to the
possible security issues, but I'm sure you could replace it with some
more/better code. This is just an idea.
Jan 27 '06 #3
On 26 Jan 2006 15:40:47 -0800, "Murali" <ma*********@gmail.com> wrote:
In Python, dictionaries can have any hashable value as a string. In
particular I can say

d = {}
d[(1,2)] = "Right"
d["(1,2)"] = "Wrong"
d["key"] = "test"

In order to print "test" using % substitution I can say

print "%(key)s" % d

Is there a way to print "Right" using % substitution?

print "%((1,2))s" % d

gives me "Wrong". Is there any syntax which will allow me to get
"Right" using % substitution?


You can modify the dict to try to convert the string to what it is
a source for, by eval, and try that as a key also, if you have no security worries
about malevolent format strings:
class D(dict): ... def __getitem__(self, key):
... print repr(key)
... if key in self: return dict.__getitem__(self, key)
... else: return self[eval(key)]
... d = D()
d[(1,2)] = "Right"
d["key"] = "test"
print "%(key)s" % d 'key'
test print "%((1,2))s" % d '(1,2)'
(1, 2)
Right d[123] = 'onetwothree'
print "%(123)s" % d '123'
123
onetwothree

Note recursive printing of converted key when the first one fails.
Of course if you _also_ define the string key for Wrong, that will
succeed, so it won't get converted to get Right:
d["(1,2)"] = "Wrong"
print "%((1,2))s" % d '(1,2)'
Wrong d[(1,2)]

(1, 2)
'Right'

Do you have a real use case? Just curious.

Regards,
Bengt Richter
Jan 27 '06 #4
No. I dont have a real life example. I was explaining % substitution to
somebody and realized that I have only used it in the form where the
keys are strings. Was wondering if there is some special syntax already
part of python with which I can lookup the dictionary using a tuple as
a key.

- Murali

Jan 28 '06 #5
On Fri, 27 Jan 2006 15:54:30 -0800, Murali wrote:
No. I dont have a real life example. I was explaining % substitution to
somebody and realized that I have only used it in the form where the
keys are strings. Was wondering if there is some special syntax already
part of python with which I can lookup the dictionary using a tuple as
a key.


print "%s" % some_dictionary[some_tuple]

Or for that matter:

print "%s" % some_dictionary[any hashable object at all]

What you can't do is use string interpolation like this:

print "%(123)s" % some_dictionary

unless the string "123" is a key in the dictionary. Having a key 123 will
not work, and the same for any other object.

--
Steven.

Jan 28 '06 #6

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

Similar topics

226
by: Stephen C. Waterbury | last post by:
This seems like it ought to work, according to the description of reduce(), but it doesn't. Is this a bug, or am I missing something? Python 2.3.2 (#1, Oct 20 2003, 01:04:35) on linux2 Type...
6
by: David Opstad | last post by:
I have a question about text rendering I'm hoping someone here can answer. Is there a way of doing linguistically correct rendering of Unicode strings in Python? In simple cases like Latin or...
22
by: Kamilche | last post by:
I've looked at a few alternatives for encryption with Python, and didn't come up anything very speedy. I've written an encryption algorithm in pure Python that can process 22 megs of data a...
46
by: tnozh | last post by:
Hi, I am blessed with a *very* gifted nine-years old daughter for whom I have recently installed an old GNU/Linux Mandrake 7.2 on an equally old Pentium Pro box. She is enjoying it tremendously...
5
by: Vamsee Krishna Gomatam | last post by:
Hello, I'm having some problems understanding Regexps in Python. I want to replace "<google>PHRASE</google>" with "<a href=http://www.google.com/search?q=PHRASE>PHRASE</a>" in a block of text....
8
by: Vittorio | last post by:
I am reading "Beginning Python from Novice to Professional" and the book is really awesome. Nonetheless on ch 13 "Database Support" I found this code to import data (in a txt file) into a SQLite...
10
by: Sullivan WxPyQtKinter | last post by:
Hi, everyone. Simply put, what I need most now is a python lib to generate simple HTML. I am now using XML to store my lab report records. I found python really convinient to manipulate XML, so...
14
by: Rochester | last post by:
Hi, I just found out that the general open file mechanism doesn't work for named pipes (fifo). Say I wrote something like this and it simply hangs python: #!/usr/bin/python import os
5
by: antar2 | last post by:
Hello, I am a beginner in Python and am not able to use a list element for regular expression, substitutions. list1 = list2 = Suppose that I want to substitute the vowels from list2 that...
0
by: taylorcarr | last post by:
A Canon printer is a smart device known for being advanced, efficient, and reliable. It is designed for home, office, and hybrid workspace use and can also be used for a variety of purposes. However,...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: aa123db | last post by:
Variable and constants Use var or let for variables and const fror constants. Var foo ='bar'; Let foo ='bar';const baz ='bar'; Functions function $name$ ($parameters$) { } ...
0
by: ryjfgjl | last post by:
If we have dozens or hundreds of excel to import into the database, if we use the excel import function provided by database editors such as navicat, it will be extremely tedious and time-consuming...
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
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...

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.