1

我正在做一些 Google python 练习,这个是关于字符串的。

我遇到过一个要求切换两个字符串中每一个的前两个字母的地方。

所以它创建了一个名为 mix_up 的函数,您基本上必须创建定义。所以基本上我做了两个变量来保存前两个字母,然后我使用替换函数,然后将它们加在一起,它应该可以工作。但相反,我将原始字符串加在一起,字母没有切换。

def mix_up(a, b):
    first = a[0:2]
    second = b[0:2]
    a.replace(first, second)
    b.replace(second, first)
    phrase = a + " " + b
    return phrase
4

3 回答 3

3

Note that replace() will replace all of the occurrences, not just the first, unless you specify otherwise. You can do this easily enough with something like:

def mix_up(a, b):
    new_a = b[0:2] + a[2:]
    new_b = a[0:2] + b[2:]
    phrase = new_a + " " + new_b
    return phrase

or more concisely:

def mix_up(a, b):
    return b[0:2] + a[2:] + " " + a[0:2] + b[2:]

You can also do replace(first, second, 1), where that last argument is the maximum number of occurrences to replace.

于 2013-10-20T03:30:41.153 回答
3

问题是该replace方法返回一个新字符串,而不是更改原始字符串。

试试这个:

a = a.replace(first, second)
b = b.replace(second, first)
于 2013-10-20T03:25:34.887 回答
2

replace不是破坏性的,它会创建一个新对象。

所以重新分配你的价值观,例如:a = a.replace(first, second)

于 2013-10-20T03:25:41.590 回答