Question on List
cwitts at gmail.com
Fri Jun 27 05:59:51 EDT 2008
On Jun 27, 9:51 am, subhabrata.i... at hotmail.com wrote:
> Dear All,
> I am trying to write the following code:
> def try1(n):
> a1="God Godess Borother Sister Family"
> a3=raw_input("PRINT A WORD")
> print a4
> if a4>0:
> print "The new word is"
> print a7
> print a5
> elif a4<0:
> print "The word is not availiable in String"
> print a11
> print a5
> print "Error"
> Now, my question is I like to see a5 or the empty list as appended
> with elements. Results I am getting is a5 giving single value like
> ['God'],['Godess']... but I like to see it as ['God','Godess'...] etc.
> Am I going wrong?
> Do I have to rethink it in some other way?
> If any one can kindly let me know.
> Best Regards,
First notes, the string .find() method return -1 for not found and
zero or above if the search string is present. Remember you count
from zero. Secondly, list .append() methods do not return a new list
but modify the list in place. Thirdly, the .index() method of a list
requires an integer and not a string. And lastly, indentation should
be 4 spaces not 8.
Just doing a sloppy job on the code (and my interpretation of what you
new_list = 
input_string="God Godess Borother Sister Family"
user_selection=raw_input("PRINT A WORD")
if input_string.find(user_selection) > -1:
s = input_string.split()
i = [i for i,j in enumerate(s) if j == user_selection]
new_word = s[i+1]
print 'The new word is %s' % new_word
print 'User selection of "%s" not in the string.' %
n -= 1
Obviously I'm going to assume that the code you posted excluded your
loop control for the "try n amount of times". What was most likely
the cause is that you loop through your structure for every attempt of
the n times but each time you reset your list when you re-create it.
Hope that helps some.
More information about the Python-list