我正在研究Python 3,却被一个非常简单的练习所阻塞:
使用方括号符号将字符串“ Do n't panic”转换为“ on tap”。
这是我的代码:
phrase = "Don't panic!"
plist = list(phrase)
new_phrase = ''.join(plist[1:3]).join(plist[5:3:-1]).join(plist[-5:-7:-1])
print(new_phrase)
我希望在输出中包含字符串“ on tap”
''.join(plist[1:3]) //"on"
.join(plist[5:3:-1]) //" t"
.join(plist[-5:-7:-1]) //"ap"
但是我有一个“ ontp”。
为什么?!?
注意:我知道还有其他方法可以解决此练习,并且我可以通过其他方式解决。我不是在寻找替代解决方案,而是想了解我上面编写的代码出了什么问题。
答案 0 :(得分:3)
只需添加您的元素,而不是尝试通过其上一个元素来加入其内容。
phrase = "Don't panic!"
plist = list(phrase)
new_phrase = ''.join(plist[1:3]) + ''.join(plist[5:3:-1]) + ''.join(plist[-5:-7:-1])
print(new_phrase) # -> on tap
您的代码无效,因为您是通过[" ", "t"]
和["a", "p"]
的先前元素加入的:
"a ontp"
| - joined
_________________________________
| |
" ont" |
| - joined |
_______________________ |
| | |
"on" [" ", "t"] ["a", "p"]
| | |
''.join(plist[1:3]).join(plist[5:3:-1]).join(plist[-5:-7:-1])
答案 1 :(得分:1)
将.join()
插入括号内的每个元素之前,将其分隔开:
'---'.join( "..." ) ==> .---.---.
您正在链接调用-因此,每个结果都将插入到以下联接部分:
phrase = "Don't panic!"
plist = list(phrase)
np1 = ''.join(plist[1:3]) # with itermediate results, see output
np2 = np1.join(plist[5:3:-1]) # the slice is "t ", it puts 'on' between " " and "t"
np3 = np2.join(plist[-5:-7:-1]) # the slice is "ap", it puts " ont" between
# 'a' and 'p'
print(np1,np2,np3 ) # ('on', ' ont', 'a ontp')
替代解决方案:
print( phrase[1:3]+phrase[5:3:-1]+phrase[7:5:-1] )
礼物:
on tap
答案 2 :(得分:1)
Each successive join is utilizing what is in front to...well..join the elements with. This is why your code gives that result. as a recommendation, print the intermediates.
phrase = "Don't panic!"
plist = list(phrase)
new_phrase = ''.join(plist[1:3]).join(plist[5:3:-1]).join(plist[-5:-7:-1])
print(''.join(plist[1:3])) #'on'
print(plist[5:3:-1]) #[' ','t']
print(''.join(plist[1:3]).join(plist[5:3:-1])) #' ont'
print(plist[-5:-7:-1]) #['a','p']
print(new_phrase) #a ontp
答案 3 :(得分:0)
如果创建字符串切片,效率会更高
phrase = "Don't panic!"
new_pharse = phrase[1:3] + phrase[5:3:-1] + phrase[-5:-7:-1]
print(new_pharse)
答案 4 :(得分:0)
以您为例
something.join(somethingElse)
某些事物将成为其他事物的间隙。 因此,在代码中,每次使用联接时,您所使用的都是先插入联接。就是这样。