# example is wrong, does not swap, only puts first in the back. see below for fix
text = ' '.join( t[1:]+t[0] for t in "Hello World".split() )
print (text)
# t[-1] is the last character put to the front,
# followed by t[1:-1] 1st to (but not including) the last character
# followed by t[0] the first character
text = ' '.join( t[-1]+t[1:-1]+t[0] for t in "Hello World".split() )
print (text)
您可以拆分字符串,交换每个单词的字母,然后.join()将其重新组合在一起:
输出:
它使用list comprehensionst提取每个被拆分的单词(
t
)-列表切片将前面的字母移到后面(t[1:]+t[0]
),并使用' '.join()
将字符串列表移回字符串。你知道吗链接:
它也适用于较长的字符串:
正如@cumulation所指出的,我误读了这个问题——我的示例只是将第一个字母放在字符串的末尾,这只会将交换第一个和最后一个字母所做的工作减半:
输出:
字符串是不可变的,因此可以通过切片创建新字符串:
要执行多个单词,请按如下方式拆分并重新连接:
通过在空格字符上拆分来列出单词
然后用你的脚本迭代这个列表
相关问题 更多 >
编程相关推荐