June 24, 2004
I'm learning Python, and it's great fun. This is my first programming language ever, so everything's kind of fun, even the more trivial things, like traversing a string and reversing the characters. Which is what I want to talk about. Here's my code:
a = raw_input("String? ")
n = len(a)
if n == 1:
print "Your string is", n, "character long."
else:
print "Your string is", n, "characters long."
while n > 0:
print a[n-1],
n = n-1
This program asks for an input and checks the length of it. If the length is 1, it prints the singular form of "character" (along with the rest, of course). If it's not 1, it prints the plural form. It then proceeds to print the n-minus-1-th character in n
(which is our string) and subtracts 1 from n
every time through the while
loop. The comma at the end of the print
statement suppresses the line break, but it still adds a space between all the characters, which is annoying. Thankfully, Michael helped me out:
a = raw_input("String? ")
n = len(a)
i = ""
if n == 1:
print "Your string is", n, "character long."
else:
print "Your string is", n, "characters long."
while n > 0:
i = i+a[n-1]
n = n-1
print i
This does almost the same thing, except it uses concatenation, which eliminates the spaces between the characters, and waits until the end to print the reversed string. Thanks Michael. :-)