|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
Complete the swapEnds() function, which takes three arguments: a string of 3 or more characters, plus two positive integers representing index positions within that string. The function returns a new string according to the following process:
• If either index value is invalid (greater than or equal to the length of the string), or if the index values are equal to one another, return the original string
• If the first index is greater than the second index, swap their values (see below for a tip on how to do this easily)
• Finally, return a new string that consists of the following sections of the original string, in this order:
1. All of the characters from the original string, from the character after the second index through the end 2. All of the characters from the first index through the second index
3. All of the characters from the beginning of the string up to (but not including) the first index
For example, consider the string “sesquipedalian”, with a first index value of 10 and a second index value of 5. The first index is greater than the second index, so we exchange their values to get 5 and 10. We now have three substrings:
• “ian” (the characters from index 11 through the end of the string)
• “ipedal” (the characters from index 5 through index 10)
• “sesqu” (the characters from the beginning of the string up to, but not including, index 5)
Combining these strings using the + operator, we get a final result of “ianipedalsesqu”.
Hint: Python provides a simple way to exchange the values of two variables using something called multiple assignment:
a, b = b, a
Examples:
Function Call
Return Value
swapEnds("space: the final frontier", 5, 14)
l frontier: the finaspace
swapEnds("these are the voyages", 12, 7)
voyagesre thethese a(with a leading space)
swapEnds("where no one has gone before", 8, 42)
where no one has gone before(no change) |
|