HI guys,
How do you write Perl's
print a ... z, A ... Z, "\n"' in Python
In Python?
A way I came up with is the following, but I'm sure this is ugly.
''.join(chr(c) for c in (range(ord('a') , ord('z')+1) +
range(ord('A'), ord('Z')+1)))
or
crange = lambda c1, c2: [ chr(c) for c in range(ord(c1), ord(c2)+1) ]
''.join(chr(c) for c in crange('a', 'z') + crange('A', 'Z'))
I want to feel The Zen of Python :) 8 7470
js:
crange = lambda c1, c2: [ chr(c) for c in range(ord(c1), ord(c2)+1) ]
''.join(chr(c) for c in crange('a', 'z') + crange('A', 'Z'))
Yes, managing char ranges is a bit of pain with Python.
You can also pack those chars:
xcrange = lambda cc: (chr(c) for c in xrange(ord(cc[0]), ord(cc[1])
+1))
But I don't like that much.
The calls:
''.join(xcrange ('az')) + ''.join(xcrange ('AZ'))
But note that you return the last item of the range too, and that goes
against the semantic of the usual Python range/xrange, so you may want
to call this function with another name.
Maybe there are better ways to solve this problem. Maybe a way to
generate (closed?) char ranges can be added to the Python standard
lib.
Bye,
bearophile
But note that you return the last item of the range too, and that goes
against the semantic of the usual Python range/xrange, so you may want
to call this function with another name.
That makes sense. 100% agree with you.
Maybe there are better ways to solve this problem. Maybe a way to
generate (closed?) char ranges can be added to the Python standard
lib.
Maybe we don't want char range If string constants would be rich enough.
js wrote:
A way I came up with is the following, but I'm sure this is ugly.
You could abuse __getitem__ (terribly, heh!) and use slice syntax...
class crange():
def __init__(self):
self.valid = range(47,58) + range(65,91) + range(97,123)
def __getitem__(sel f, s):
if isinstance(s, slice):
start, stop = s.start, s.stop
if not start: start = '0'
if isinstance(stop , int) and stop 122: stop = 'z'
elif not stop: stop = 'z'
clist = []
chars = range(ord(start ), ord(stop)+1)
for i in range(len(chars )):
if chars[i] in self.valid:
clist.append(ch r(chars[i]))
return ''.join(clist)
else:
return s
cr = crange()
print cr['A':'z']
print cr['0':'8']
print cr[:]
Regards,
Jordan
"js " <eb*****@gmail. comwrites:
>But note that you return the last item of the range too, and that goes against the semantic of the usual Python range/xrange, so you may want to call this function with another name.
That makes sense. 100% agree with you.
>Maybe there are better ways to solve this problem. Maybe a way to generate (closed?) char ranges can be added to the Python standard lib.
Maybe we don't want char range If string constants would be rich
enough.
But as soon as we want a string that doesn't correspond to any
pre-defined constants, we're hosed. For example, there isn't
a constant that would correspond to this Perl-ism:
print l ... w, e ... j, L ... W, E ... J, "\n";
--
Lloyd Zusman lj*@asfast.com
God bless you.
Maybe we don't want char range If string constants would be rich
enough.
But as soon as we want a string that doesn't correspond to any
pre-defined constants, we're hosed. For example, there isn't
a constant that would correspond to this Perl-ism:
print l ... w, e ... j, L ... W, E ... J, "\n";
Yes, I'm certain that l ... w, e ..j will never be a constant
because that doesn't mean a thing so nobody want them :)
js <eb*****@gmail. comwrote:
HI guys,
How do you write Perl's
print a ... z, A ... Z, "\n"' in Python
In Python?
This specific one is easy, though this doesn't generalize:
import string
print string.lowercas e + string.uppercas e
For the general case, there's no way to avoid calling chr and ord,
because a string in Python doesn't have a "natural successor". So the
only issue is how you prefer to hide those calls &c (in some class or
function) and you already received suggestions on that.
Alex al***@mac.com (Alex Martelli) wrote in
news:1hue4db.1i fwnsjmhm2pN%al* **@mac.com:
js <eb*****@gmail. comwrote:
>HI guys,
How do you write Perl's
print a ... z, A ... Z, "\n"' in Python
In Python?
This specific one is easy, though this doesn't generalize:
import string
print string.lowercas e + string.uppercas e
For the general case, there's no way to avoid calling chr and
ord, because a string in Python doesn't have a "natural
successor". So the only issue is how you prefer to hide those
calls &c (in some class or function) and you already received
suggestions on that.
No ord or chr in sight:
# Inclusive character range.
def pycrange(lo,hi) :
import string
chars = string.letters + " "
rstr = ''
lp = chars.find(lo)
hp = chars.find(hi)
if lp < hp:
rstr = chars[lp:hp+1]
return rstr
print pycrange('c','n ')
Lame code, though.
--
rzed
rzed <rz*****@gmail. comwrote: al***@mac.com (Alex Martelli) wrote in
news:1hue4db.1i fwnsjmhm2pN%al* **@mac.com:
js <eb*****@gmail. comwrote:
HI guys,
How do you write Perl's
print a ... z, A ... Z, "\n"' in Python
In Python?
This specific one is easy, though this doesn't generalize:
import string
print string.lowercas e + string.uppercas e
For the general case, there's no way to avoid calling chr and
ord, because a string in Python doesn't have a "natural
successor". So the only issue is how you prefer to hide those
calls &c (in some class or function) and you already received
suggestions on that.
No ord or chr in sight:
# Inclusive character range.
def pycrange(lo,hi) :
import string
chars = string.letters + " "
rstr = ''
lp = chars.find(lo)
hp = chars.find(hi)
if lp < hp:
rstr = chars[lp:hp+1]
return rstr
print pycrange('c','n ')
Lame code, though.
Very (the very existence of rstr and the if block are redundant, for
example; "return chars[lp:hp+1]" will already return an empty string
when lp hp, and it's weird for the result to be empty for equal
arguments lo and hi when it's a length-two string for arguments, say,
'a' and 'b').
Also incorrect, presumably, since it would e.g. consider pycrange('w',
'C') to be 'wxyzABC', rather than empty (as an ord/chr based solution
would) or 'wxyz' (as I believe Perl does for 'w'...'C' -- one of those
black-magical Perl things, unless they've changed it recently) -- in
ASCII, uppercase letters come before lowercase ones, but in
string.letters they're vice versa.
Sure, you can get a complete 256-char ASCII alphabet with
alp=string.make trans('', ''), use alp.find(x) as roughly equivalent to
ord(x) and alp[y] as roughly equivalent to chr(y), and thus (or by
sillier tricks yet) you wouldn't _formally_ "be calling chr and ord"
(you'd instead use roughly equivalent but slower and murkier idioms).
However, my point was: you can't avoid transforming from characters to
numbers and back again (ord and chr are just the "one obvious way" to do
that -- correct, if you want ASCII, readable, direct, and fast). .find
and indexing (instead of ord and chr) do give you more flexibility (to
use an underlying order that's not ASCII's) should you need that; and
slicing an appropriate string does avoid an explicit loop.
(Just trying to forestall further silliness...): other ways to avoid
"calling chr and ord" include abusing modules struct and array.
Alex This thread has been closed and replies have been disabled. Please start a new discussion. Similar topics |
by: John Baker |
last post by:
HI;
I feel like a fool..I put CUTE FTP in my last request for help --it should have been CUTE
PDF! I have FTP on my mind because I have been working on a web based application, and
somehow my brain got stuck on it..sorry!
Hi:
I need some help writing code that will "print" a report using Cute PDF.
|
by: Paul Sullivan |
last post by:
We are a state agency that views protected medical information via our
intranet. The screens even have privacy shields. Alarmingly, uses can
"Print" and "Save As" which destroys the protection of the health
information at the level we want.
QUESTION: Can we shut those off?? Any other suggestions??
Paul Sullivan
|
by: Jeremy L. Moles |
last post by:
I have an object (written as part C extension, part pure Python) called
foo that I've been using without much fuss for a few months now.
However, in my latest project (a rather large one involving
multi-threading, pygtk, etc.), I'm seeing some really strange behavior
with a particular instance of my foo object.
About midway through my program, any attempt to use the instance fails;
however, if I add print statements before trying to...
|
by: Steff |
last post by:
I am wandering if my code is making sense... I use a lot the print function.
Is it weird in this case where I have to display an array ? I thought it
would be better to have the entire array in php but now I am not sure if
that makes sense. Can you tell me please ?
<html>
<head>
|
by: kbperry |
last post by:
Hi all,
I am getting an error message when trying to use the P4 print command
via the python api for perforce.
Anytime that I run p4c.run("print","-q", eachFile), I keep getting an
error message: "AttributeError: OutputBinary."
Here is my code below: Please Help.
| |
by: Appu |
last post by:
How to Check in the window print dialog box whether we clicked either
"print" or "cancel".
while clicking a button i call wnidow.print() to pop up the windows
PRint Dialog box. I want to check whether the user clicked either
"print" or "cancel" in that print dialog box of windows.
Please Help soon.
Thanks
T.Appasamy
|
by: Prisoner at War |
last post by:
Hi, your friendly neighborhood n00b here, just wondering why on earth
the Py3K folks want to mess with a simple thing like the "print"
"command" (is that what it's called, a command?), turning it into
"print()"...I mean, what's the point, exactly?? To look like a more
"traditional" computer-language format?
And what's with not supporting the so-called softspace "feature" of
the current "print" command, where a space after a comma, like
|
by: TP |
last post by:
Hi everybody,
All my problem is in the title.
If I try:
$ python -c 'print "foo",'
It does not change anything, surely because the line return is added
by "python -c".
|
by: Cameron Simpson |
last post by:
On 18Aug2008 11:58, Beema Shafreen <beema.shafreen@gmail.comwrote:
| In my script i have to print a series of string , so
|
| print "%s\t%s\t%s\t%s\t%s\t%s\t" %("a","v","t","R","s","f")
|
| I need to know instead of typing so many %s can i write %6s in python, as
| we do in C progm.
I hate to tell you this, but "%6s" in C does NOT print 6 strings. It
prints 1 string, right justified, in no less that 6 characters.
|
by: sixtyfootersdude |
last post by:
Good Morning!
I am just starting to learn perl and I am somewhat mistifide about when I should do:
print("@input");
and when I should do:
print(@input)
|
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...
| |
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...
|
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,...
|
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...
|
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, and deployment—without human intervention. Imagine an AI that can take a project description, break it down, write the code, debug it, and then launch it, all on its own....
Now, this would greatly impact the work of software developers. The idea...
|
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...
|
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();...
| |
by: adsilva |
last post by:
A Windows Forms form does not have the event Unload, like VB6. What one acts like?
|
by: muto222 |
last post by:
How can i add a mobile payment intergratation into php mysql website.
| | |