Reputation: 13
New to python. Trying to understand string slicing and methods. Have been given the following codes to read and state what they will display. Can someone please explain how the second program displays the reverse order?
I have searched for the answer, and only come up with slicing methods to reverse using negative numbers but not this way.
program 1:
str1 = 'Wednesday Thursday Friday'
new_string = ''
index = 0
while index < len(str1):
if str1[index].isupper():
new_string = new_string + str1[index]
index = index + 1
new_string = new_string + '!?!'
print(new_string)
program 2:
str1 = 'Wednesday Thursday Friday'
new_string = ''
index = 0
while index < len(str1):
if str1[index].isupper():
new_string = str1[index] + new_string
index = index + 1
new_string = new_string + '!?!'
print(new_string)
I understand the first program and get the result WTF!?!
Do not understand why the second program is FTW!?!
Upvotes: 0
Views: 122
Reputation: 67
The only difference between these two programs is that the first has the line
new_string = new_string + str1[index]
whereas the second has the line
new_string = str1[index] + new_string
In the first one, you take the string you're building up and add the next capital letter found to its end. In the second one, you take the string you're building up and add the next capital letter found to its front. So, in the first, the values of new_string are:
'W'
'WT'
'WTF'
In the second string, the values of new_string are:
'W'
'TW'
'FTW'
Hence, you end up reversing the string. Basically, in the first method you just add letters as you find them, but in the second method you move letters back one place each time you add another, leading to the first letter found being the last letter in the end string, and so on.
On another note, in Python its not usually necessary to iterate through strings or lists using a while loop and the index as is done in both programs. For example, the lines
index = 0
while index < len(str1):
if str1[index].isupper():
could be replaced with
for letter in str1:
if letter.isupper():
which is slightly neater. We could even replaced the entirety of program 1 as below:
str1 = 'Wednesday Thursday Friday'
# The below line uses 'list comprehensions'
new_string = ''.join(letter for letter in str1 if letter.isupper())
new_string = new_string + '!?!'
print(new_string)
I recommend that you read through the python tutorial if you're looking for more information on any of this! :)
Upvotes: 1
Reputation: 1079
The only difference, like uneven_mark correctly stated, is
new_string = new_string + str1[index]
and
new_string = str1[index] + new_string
this is just because they are being added in the reverse order, think through the whole program and each of its steps in your head prior to this line and it will make sense :)
Upvotes: 0