Python iteration program: print strings in a list that start with a specific character -
before begin question beginner student taking introduction python course @ school, apologies if question not worded, , suggestions welcome.
the question struggling so: "create program requests list of names user , print names starting through i."
so far code have had no luck figuring out doing wrong:
students = input('enter list of students: ') s in students: if students[:1] == 'abcdefghiabcdefghi': print(s) any answers appreciated, thank time in advance.
your problem appears here:
if students[:1] == 'abcdefghiabcdefghi': this check false. str1 == str2 true, strings have same length, , have same characters in same order. students[:-1] going either 0 or 1 character long, can't ever equal longer string on right. check if character any of ones in long string, can use in operator:
if students[:1] in 'abcdefghiabcdefghi': but note true if students empty string '', might not want. can use students[0] instead guard against (the empty string cause error instead of false positive), better way use str.startswith method this:
if students.startswith(tuple('abcdefghiabcdefghi')): the tuple call there turn string tuple ('a', 'b', 'c', ...) - might choose put tuple literal directly in code instead. need argument tuple, because startswith (like ==) checks strings of length - handing tuple of possible prefixes checks of them individually , true if of them match.
also, more common way case-insensitive check force test string case want; trick come in handy when have test strings longer 1 character - works this:
if students.upper().startswith(tuple("abcdefghi")):
Comments
Post a Comment