好的,所以我在将一个字符串的一部分与列表中另一个字符串的一部分交换时遇到了一个问题。我在这个网站上也看到过其他类似的问题,但似乎没有一个对我有用。在
假设我有一个列表:
sentList = ['i like math', 'i am a cs expert']
现在我想使用由用户输入确定的变量将“math”与“cs”切换。在
^{pr2}$那么,现在我该如何交换这两个选项,以便我的列表返回以下内容:
sentList = ['i like cs', 'i am a math expert']
一如既往,谢谢你的帮助。我想我可以使用替换功能,但不确定如何使用。我想应该是这样的:
sentList = [sentListN.replace(currentWord, newWord) for sentListN in sentList]
但是,很明显这是行不通的。在
你可以通过简单的交换函数来实现。不需要使代码复杂化:)
一个使用
list comprehension
的单行程序。在所以
^{pr2}$在这里,}替换为
if sent.find('math')>=0
将发现字符串是否包含'math'
,如果是,则将其替换为'cs'
,否则它将{'math'
。如果字符串既不包含,也将打印原始字符串,因为只有找到子字符串时,replace才起作用。在编辑:正如@Rawing指出的,上面的代码中有一些错误。所以这里有新的代码可以处理所有的情况。在
我已经使用},其中我们引入一个临时变量
re.sub
来处理只有单词的替换,替换算法就是如何交换两个变量,比如x
和{t
来帮助交换:t = x; x = y; y = t
。选择这种方法是因为我们必须同时进行多次替换。在所以这次在一个更大的测试用例中,我们得到:
下面的代码可以工作。我使用word1(currentWord)和word2(newWord)变量作为用户输入
如果我们把它分解成台阶,看起来像
^{pr2}$相关问题 更多 >
编程相关推荐