473,791 Members | 3,122 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 #1
16 2090
Scott wrote:
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.
Homework?

Anyway, what about:

for c in string[::-1]:
print c
Stefan
Jun 27 '07 #2
On Wed, Jun 27, 2007 at 12:53:36PM -0400, Scott wrote:
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.
>>def rev(forward):
... backward = list(forward)
... backward.revers e()
... return ''.join(backwar d)
>>rev("spam")
'maps'

list.reverse() changes the list in-place. Instead of iterating over
the items in the string sequence, you can just convert the input
string outright.

--

[Will Maier]-----------------[wi*******@ml1.n et|http://www.lfod.us/]
Jun 27 '07 #3
Scott wrote:
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.                 >>>>mylist = []
  4. def rev(x):
  •  
  •             for char in x:
  •                 mylist.append(char)
  •                 mylist.reverse()
  •                 print mylist
  •  
  • <snip/>

    The reverse() is totally useless to apply each when appending each
    character. Not only useless, but faulty: if you have a even number of
    characters, your string won't be reversed.

    All you need to do is this:
    >>x = "abcdefg"
    print "".join(reverse d(x))
    gfedcba
    HTH Diez
    Jun 27 '07 #4

    "Scott" <s_*********@co mcast.netwrote in message
    news:cY******** *************** *******@comcast .com...
    | 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.
    >>'this is a test'[::-1]
    'tset a si siht'

    Jun 27 '07 #5
    On 2007-06-27, Scott <s_*********@co mcast.netwrote:
    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.
    No, it just wants to to print the characters in reverse, one per
    line.
    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:
    >>>>mylist = []
    That's bad. If you need to use a list in the rev function, you
    should bind a new list to a local variable inside rev.
    >>>>def rev(x):
    for char in x:
    mylist.append(c har)
    mylist.reverse( )
    print mylist
    Here's an debugging exercise that you should try.

    Please explain what you think each line in the above is supposed
    to do. Pretend you are trying to convince me that the above
    program works correctly. I bet you will see find your errors
    right away as a result of this exercise.
    [/code]
    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:
    Experimentation with stuff you don't fully understand is a great
    way to learn, but not that useful for solving exercises. ;)

    --
    Neil Cerutti
    This team is one execution away from being a very good basketball team. --Doc
    Rivers
    Jun 27 '07 #6
    ptn
    >>>mylist = []

    That's bad. If you need to use a list in the rev function, you
    should bind a new list to a local variable inside rev.
    He's right. If you want to use a list to temporarily store the
    reversed version of your string, it should exist only in the local
    namespace of your function.

    There's still stuff you can do with your function to make it work,
    such as:
    >>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])
    So, big lessons: (1) Global variables suck if you try to manipulate
    them and (2) in Python, if your code isn't as clear as you would like,
    there's probably a better way to do it.

    Jun 28 '07 #7
    ptn <tn******@gmail .comwrote in news:1182997438 .541012.54100
    @o61g2000hsh.go oglegroups.com:
    >
    >>>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?

    Martin
    Jul 1 '07 #8
    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.

    Slicing is one of Pythons great features, but even experienced programmers
    often forget that you can have a third argument to a slice or that it can
    even be negative.

    The syntax for joining a sequence of strings with a separator is ugly, I
    sometimes prefer to write it out as:
    print str.join('\n', whatever)
    or:
    joinlines = '\n'.join
    ...
    print joinlines(whate ver)

    but in this case I'd be as likely to go for an explicit loop for the print:

    def rev(x):
    for letter in x[::-1]:
    print letter

    which I think hits about the optimum between brevity and clarity. Your own
    optimum point may of course vary.
    Jul 1 '07 #9
    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?
    thanks
    Martin

    Jul 1 '07 #10

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

    Similar topics

    4
    5975
    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
    10155
    by: minguskhan | last post by:
    Does anyone know how to reverse a string using a loop?
    5
    1352
    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
    6657
    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
    12070
    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
    6104
    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
    3313
    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
    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...
    0
    9023
    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
    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();...
    0
    5424
    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 the same network. But I'm wondering if it's possible to do the same thing, with 2 Pfsense firewalls...
    2
    3709
    muto222
    by: muto222 | last post by:
    How can i add a mobile payment intergratation into php mysql website.
    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.