473,804 Members | 3,196 Online
Bytes | Software Development & Data Engineering Community
+ Post

Home Posts Topics Members FAQ

Reversing a string

Yeah I know strings == immutable, but question 1 in section 7.14 of "How to
think like a computer Scientist" has me trying to reverse one.

I've come up with two things, one works almost like it should except that
every traversal thru the string I've gotten it to repeat the "list" again.
This is what it looks like:

Expand|Select|Wrap|Line Numbers
  1.         
  2.                         
  3.                         
  4.                 >>>mylist = []
  5. def rev(x):
  6.  
  7. for char in x:
  8. mylist.append(char)
  9. mylist.reverse()
  10. print mylist
  11.  
And the output that sorta works like it should, but threw a curveball, at me
looks like this:
>>rev("this is just a test")
['t']
['h', 't']
['i', 't', 'h']
['s', 'h', 't', 'i']
[' ', 'i', 't', 'h', 's']
['i', 's', 'h', 't', 'i', ' ']
['s', ' ', 'i', 't', 'h', 's', 'i']
[' ', 'i', 's', 'h', 't', 'i', ' ', 's']
['j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ']
['u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j']
['s', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u']
['t', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's']
[' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't']
['a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's', ' ']
[' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't', 'a']
['t', 'a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's', ' ',
' ']
['e', ' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u', 't',
'a', 't']
['s', 't', 'a', 't', 'u', ' ', 'i', 's', 'h', 't', 'i', ' ', 's', 'j', 's',
' ', ' ', 'e']
['t', 'e', ' ', ' ', 's', 'j', 's', ' ', 'i', 't', 'h', 's', 'i', ' ', 'u',
't', 'a', 't', 's']
So I figured maybe make it a generator (I'm not TO familiar with generators
yet so don't laugh) which changed my code just a slight bit:

Expand|Select|Wrap|Line Numbers
  1.         
  2.                         
  3.                         
  4.                 >>>mylist = []
  5. def rev(x):
  6.  
  7. for char in x:
  8. mylist.append(char)
  9. mylist.reverse()
  10. yield mylist
  11.  
But even that threw me a curveball:
>>rev("this is just a test")
<generator object at 0x00D52170>

So how on earth would be the best way to: Write a function that takes a
string as an argument and outputs the letters backward, one per line.

It should look like the first char of every list in the top "working" code.

Any help woould be greatly apreciated, and a little bit of explaination as
to why you did it the way you did would be more helpful than just the code.

Thanks in advance
Jun 27 '07
16 2094
Martin Durkin wrote:
Duncan Booth <du**********@i nvalid.invalidw rote in
news:Xn******** *************** **@127.0.0.1:
>Martin Durkin <no****@william sdurkin.co.ukwr ote:
>>>>>>def rev(x):
mylist = []
for char in x:
mylist.append(c har)
mylist.reverse( )
for letter in mylist:
print letter

However, compare the incredible difference in clarity and elegance
between that and:

>>>print "\n".join("spam "[::-1])
OK, maybe I'm missing the point here as I'm new to Python. The first
one seems clearer to me. What am I missing?
I think all you are missing is familarity with Python, but I too don't
like one-liners simply for their own sake.

I guess that's it. The first one reads more like a textbook example which
is about where I am at. Is there any speed benefit from the one liner?
Almost definitely. But you can check yourself by using the timeit module.

Stefan
Jul 1 '07 #11
On 1 Jul 2007 11:09:40 GMT, Martin Durkin <no****@william sdurkin.co.ukwr ote:
Duncan Booth <du**********@i nvalid.invalidw rote in
news:Xn******** *************** **@127.0.0.1:
Martin Durkin <no****@william sdurkin.co.ukwr ote:
>>>>def rev(x):
mylist = []
for char in x:
mylist.append(c har)
mylist.reverse( )
for letter in mylist:
print letter

However, compare the incredible difference in clarity and elegance
between that and:

print "\n".join("spam "[::-1])
OK, maybe I'm missing the point here as I'm new to Python. The first
one seems clearer to me. What am I missing?
I think all you are missing is familarity with Python, but I too don't
like one-liners simply for their own sake.

I guess that's it. The first one reads more like a textbook example which
is about where I am at. Is there any speed benefit from the one liner?
The one line is quite a bit faster:

evan@thinkpad ~ $ python -m timeit 's = "onomatopoe ia"; s = s.join(s[::-1])'
100000 loops, best of 3: 6.24 usec per loop

evan@thinkpad ~ $ python -m timeit '
def rev(x):
mylist = []
for char in x:
mylist.append(c har)
mylist.reverse( )
return "".join(myl ist)

s = "onomatopoe ia"
s = rev(s)'
100000 loops, best of 3: 9.73 usec per loop

--
Evan Klitzke <ev**@yelp.co m>
Jul 1 '07 #12
Jay Loden <py****@jaylode n.comwrote:
...
For what it's worth, with python 2.5 on my Macbook:
Hmmm, doesn't look to me as if it's worth much...:
[jloden@macbook jloden]$ python -m timeit 's = "onomatopoe ia"; s =
s.join(s[::-1])'

since what you're doing is...:
>>s = "onomatopoe ia"
s = s.join(s[::-1])
s
'aonomatopoeiai onomatopoeiaeon omatopoeiaoonom atopoeiaponomat opoeiaoonoma
topoeiatonomato poeiaaonomatopo eiamonomatopoei aoonomatopoeian onomatopoeia
o'
>>>
....which isn't really just reversing the string, but quite a bit more
work!-)
Alex
Jul 1 '07 #13
Alex Martelli wrote:
Martin Durkin <no****@william sdurkin.co.ukwr ote:
...
>>>>>>>>print "\n".join("spam "[::-1])
...
>>>OK, maybe I'm missing the point here as I'm new to Python. The first
one seems clearer to me. What am I missing?

I think all you are missing is familarity with Python, but I too don't
like one-liners simply for their own sake.
I guess that's it. The first one reads more like a textbook example which
is about where I am at. Is there any speed benefit from the one liner?

The first example reads "excruciati ngly low-level" to me: its autor is
thinking in terms of what the machine is doing, mapped into pretty
elementary low-level constructs.

The second example depends first of all on knowledge of extended-slicing
(specifically the fact that x[::-1] is a reversal, because of the
negative -1 "step" aka "stride"). If you don't know about extended
slicing, you're unlikely to just "get it from context", because it uses
a syntax based on punctuation rather than readable words whose meaning
you might guess at. Python has a modest amount of such "punctuatio n
syntax" -- about the same amount as C but definitely more than Cobol
(where one would typically write "ADD a TO b" to avoid shocking totally
clueless readers with "mysterious punctuation" such as "a + b"...!!!-).
Punctuation is often very concise but not "intrinsica lly obvious" unless
you've been exposed to it already;-).
Since you mentioned Cobol I couldn't resist...

move "spam" to spam
Display Function Reverse(spam)

There's also slicing (known in Cobol as "reference modification")
move mystring(5:3) to my-newstring
* moves 3 characters starting with character 5

No "negative" slicing, though it could be simulated with Function
Reverse() and ref.mod.

Frank
Jul 2 '07 #14

Alex Martelli wrote:
since what you're doing is...:
>>>s = "onomatopoe ia"
s = s.join(s[::-1])
s
'aonomatopoeiai onomatopoeiaeon omatopoeiaoonom atopoeiaponomat opoeiaoonoma
topoeiatonomato poeiaaonomatopo eiamonomatopoei aoonomatopoeian onomatopoeia
o'

...which isn't really just reversing the string, but quite a bit more
work!-)
That's what I get for copying and pasting from the post preceding mine and not actually checking it for what it does ;)
Jul 2 '07 #15
Jan Vorwerk <ja*********@cr etin.frwrote:
[ lots of sensible stuff to discover "reversed" ]
>print reversed.__doc_ _
See also:
>>help(reversed )
--
\S -- si***@chiark.gr eenend.org.uk -- http://www.chaos.org.uk/~sion/
"Frankly I have no feelings towards penguins one way or the other"
-- Arthur C. Clarke
her nu becomeþ se bera eadward ofdun hlæddre heafdes bæce bump bump bump
Jul 5 '07 #16
al***@mac.com (Alex Martelli) wrote in
news:1i0pz5v.ef trpfbeilzpN%al* **@mac.com:
Aahz <aa**@pythoncra ft.comwrote:
>I would agree with people who claim
that you should memorize most of the built-in functions (which is
precisely why there is a high barrier to adding more built-in
functions).

I think the built-in functions and types a beginner is likely to need
are a "fuzzy subset" (the decision of whether to include or exclude
something being not really obvious:-) roughly including:

abs all any bool chr cmp dict dir enumerate float getattr help hex int
iter len list max min object open ord property raw_input reversed set
sorted str sum tuple unichr unicode xrange zip
Thanks guys, that is helpful.
Jul 5 '07 #17

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

Similar topics

4
5977
by: Kevin | last post by:
Hello, I need to some help in reversing an 2-dimensional array. I am working with gif images and I am trying to make the mirror image. I was hoping that someone could help give me a headstart in how I can accomplish this. Also, I don't know the the size of the array before hand as the image can be any size. I already have the my read and write gif functions working, but I just need to know how to reverse the contents.
3
10163
by: minguskhan | last post by:
Does anyone know how to reverse a string using a loop?
5
1353
by: Shwetabh | last post by:
Hi, How can I remove a part of string from complete string in SQL? this is something i want to do: update ace set PICTURE = PICTURE - '\\SHWETABH\Shwetabh\I\' But here ' - ' is not allowed.
4
2714
by: hello12 | last post by:
Hello, I am new to java and i was having a hard time figuring out on how to do certain string manipulations. I was asked to read in a text file and reverse the words. So far, I have put all the words in the text file into an arraylist. For example... Hello World. ---> must be printed out as --> olleH .dlroW right now when i print my arraylist i am getting I was thinking of somehow...
8
4764
by: arnuld | last post by:
i have created a solutions myself. it compiles without any trouble and runs but it prints some strange characters. i am not able to find where is the trouble. --------------------------------- PROGRAMME -------------------------------- /* K&R2 section 1.9 exercise 1.19
3
6658
by: Babikie | last post by:
Write a program that performs a reverse recursion with following functions. void swop (char,int,int); void reverse (char); void rev(char,int, int); User should enter a string and all character should be reversed. Note! The rev function should be used as the recursive function, accepting the string, plus the first and last position of string. The reverse() passes the first and the last position of the string to the rev() which performs the...
2
12071
by: Kelly B | last post by:
I tried to write a code which would reverse the order of words in a given string. I.e if Input String=The C Programming Language Output String=Language Programming C The Here is the code ..but it seems a bit "bloated" as i need an extra array of same size of the original string
3
6105
by: steezli | last post by:
Hi, Brand new to VB.NET and I'm having a problem figuring out this program. I'll try and be descritive as possible. I have to create a Windows application that contains a single top-level form with two textboxes on it, on positioned above the other. As each character is entered into the upper textbox, the string that has been entered into the upper textbox must appear in the lower textbox, but in reverse. If the input field contains...
1
3314
by: rajkumarbathula | last post by:
Hi Could any one help me out in reversing rows/elements of DataTable or String or DataList by using any simple statement? Thanks
0
9571
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
10561
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...
0
10318
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
10302
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
10069
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
9132
agi2029
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...
1
7608
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...
1
4277
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
3803
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.