Python 3.3 Given the strings s1 and s2 , not necessarily of the same length, cre
ID: 641431 • Letter: P
Question
Python 3.3
Given the strings s1 and s2 , not necessarily of the same length, create a new string consisting of alternating characters of s1 and s2 (that is, the first character of s1 followed by the first character of s2 , followed by the second character of s1 , followed by the second character of s2 , and so on. Once the end of either string is reached, the remainder of the longer string is added to the end of the new string. For example, if s1 contained "abc"and s2 contained "uvwxyz" , then the new string should contain "aubvcwxyz" . Associate the new string with the variable s3 .
Explanation / Answer
Given the strings s1 and s2 , not necessarily of the same length, create a new string consisting of alternating characters of s1 and s2 (that is, the first character of s1 followed by the first character of s2 , followed by the second character of s1 , followed by the second character of s2 , and so on. Once the end of either string is reached, the remainder of the longer string is added to the end of the new string. For example, if s1 contained "abc" and s2 contained "uvwxyz" , then the new string should contain "aubvcwxyz" . Associate the new string with the variable s3 .
s3 = ''
i = 0
while i < len(s1) and i < len(s2):
s3 += s1[i] + s2[i]
i += 1
if len(s1) > len(s2):
s3 += s1[-i:]
elif len(s2) > len(s1):
s3 += s2[-i:]
2) Assign True to the variable has_dups if the string s1 has any duplicate character (that is if any character appears more than once) and False otherwise
for i in range(len(s1)):
if s1.count(s1[i]) > 1:
has_dups = True
else: has_dups = False
3) Given a variable s that is associated with non-empty empty string, write some statements that use a while loop to associate a variable vowel_count with the number of lower-case vowels ("a","e","i","o","u") in the string .
i = 0
vowel_count = 0
while i < len(s.lower()):
if s[i].lower() in ["a","e","i","o","u"]:
vowel_count += 1
i += 1
4) Given the string line , create a set of all the vowels in line . Associate the set with the variable vowels .
vowels = []
for x in line:
if x=="a" or x=="e" or x=="i" or x=="o" or x=="u":
vowels.append(x)
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.