Ending Up


So I have this code

if len(original) > 0 and original.isalpha():
word= original.lower()
first = word[0]
new_word= word + first +pyg
new_word= new_word[1:len(new_word)]
print new_word

Why do we have to mention the new_word before the [1:len(new_word)] ?



This is a syntax that is specific to the language. It is used to slice a string contained in a variable...
You can look here and here for more.


Thank you for your answer. However, that was not the question. My question was why we needed to mention the new_word before the [1:len(new_word)] as in new_word[1:len(new_word)]


Here, the new_word before the [1:len(new_word)] is the name of the variable that contains the string you want to cut.
For example in a program you can have many variables that contain strings. So it is necessary to mention which variable contains the specific string you want to slice.


I see! Thanks! And.. What about the new_word inside the ()? Is that also the same variable as the new_word that is before the [? Thanks!


Absolutely... Inside the brackets len(new_word) returns the length of the string contained in the variable new_word..
If for exemple new_word = "i love food", then len(new_word) will return 11 which is the number of characters in new_word ie "i love food".
So new_word[1:len(new_word)] will be equivalent to new_word[1:11] here.


And what happens if we changed the new_word before the [ with another variable? Or if we change the new_word inside the () with another variable?


The output will be different.

test1= "i love food"
test2= "luke, i am your father"

print test2[0:len(test1)]


luke, i am


So the variable that is written before [ takes the priority instead of the variable inside ()?


No.. It's the opposite... In the exemple above: test2[0:len(test1)], the computer will try to calculate the length of test1 first...
He will obtain 11 then he will do now test2[0:11] and he will finally obtain luke, i am


I understood until the part where you said :

What do you mean by that? Thanks again for the fast answer.


It means that after calculating len(test1), the computer will "replace" it by his value.
test2[0:len(test1)] will become test2[0:11] because len(test1) is equal to 11.


Oh now I understand! Thank you so much for helping me, Konaesan!


You're welcome @theprotocoler :+1:


This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.