[Tutor] split a string inside a list
Dave Angel
davea at davea.name
Sat May 9 13:00:10 CEST 2015
On 05/09/2015 04:13 AM, Alan Gauld wrote:
> On 09/05/15 04:24, Kayla Hiltermann wrote:
>> i want to account for variability in user input,
> > like using commas or just spaces.
>
>> the user input is initially a string, but is converted to a list once
> > run through .split() .
> > I would like to split the user input by commas or spaces,
>
> I would first replace all non-space separators with spaces
> then do the split
>
> separators = ',.;:' # plus any others you might get
> for sep in separators:
> inString.replace(sep,' ')
inString = inString.replace(sep,' ')
> sides = inString.split()
>
>
>> import re
>>
>> def pythagorean_function():
>> sides = raw_input("Please enter three sides to a triangle:
>> \n").split(" |,")
>
>> sides_int = []
>> for value in sides:
>> try:
>> sides_int.append(int(value))
>> except ValueError:
>> continue
>
> You could use a list comprehension here, although you
> may not have seen them yet. It would look like:
>
> try:
> sides_int = [int(value) for value in sides]
> except ValueError:
> print ("Remember all sides must be integers \n")
> return # no point continuing with the function using bad data
>
>> while len(sides_int) != 3:
>> print ("you did not enter THREE sides! remember all sides must
>> be integers \n")
>> break
>
> This should just be an 'if' test, not a while loop.
> You only want to test the length once.
>
>> sides.sort()
>> if sides[0]**2 + sides[1]**2 == sides[2]**2:
>> print "\nthis triangle IS a pythagorean triple!\n"
>> else:
>> print "\nthis triangle is NOT a pythagorean triple\n"
>>
>> redo()
>
> Rather than use recursion here it would be better to
> put your function in a top level while loop.
>
>> def redo():
>> redo_question = raw_input("would you like to see if another
>> triangle is a pythagorean triple? Y/N\n")
>> if redo_question == "Y":
>> pythagorean_function()
>> else:
>> print "thanks for stopping by!"
>
> You could write that like
>
> redo_question = 'Y'
> while redo_question.upper() == 'Y':
> pythagorean_function()
> redo_question = raw_input("would you like to see if another
> triangle is a pythagorean triple? Y/N\n")
>
> print "thanks for stopping by!"
>
>
> HTH
--
DaveA
More information about the Tutor
mailing list