在2+字字符串中交换字母

2024-04-20 02:43:02 发布

您现在位置:Python中文网/ 问答频道 /正文

假设我有一个单字字符串(“Hello”),我想交换第一个和最后一个字母,所以我要这样做:

s="Hello"
l=list(s)
l[0],l[len(l)-1]=l[len(l)-1],l[0]
print("".join(l))

但是,如果我必须交换字符串中每个单词的第一个和最后一个字母:“Hello World”,这样我就可以得到“oellH dorlW”了。你知道吗

我想使用嵌套列表,但它似乎过于复杂。你知道吗


Tags: 字符串hello列表worldlen字母单词单字
3条回答

您可以拆分字符串,交换每个单词的字母,然后.join()将其重新组合在一起:

# 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)

输出:

 elloH orldW

它使用list comprehensionst提取每个被拆分的单词(t)-列表切片将前面的字母移到后面(t[1:]+t[0]),并使用' '.join()将字符串列表移回字符串。你知道吗

链接:

它也适用于较长的字符串:

elloH orldW si a eallyr verusedo trings ermt - orF ureS !

正如@cumulation所指出的,我误读了这个问题——我的示例只是将第一个字母放在字符串的末尾,这只会将交换第一个和最后一个字母所做的工作减半:

# 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)

输出:

oellH dorlW 

字符串是不可变的,因此可以通过切片创建新字符串:

s = "Hello"
>>> s[-1] + s[1:-1] + s[0]
"oellH"

要执行多个单词,请按如下方式拆分并重新连接:

s= "Hello World"
>>> ' '.join(word[-1] + word[1:-1] + word[0] for word in s.split())
'oellH dorlW'
    string  = "Hello Planet Earth"

通过在空格字符上拆分来列出单词

    words = string.split(" ")

然后用你的脚本迭代这个列表

    for word in words:
        l = list(word)
        l[0], l[len(l) - 1] = l[len(l) - 1], l[0]
        print("".join(l))

相关问题 更多 >