【问题标题】:Python 3.6: Moving around words within a stringPython 3.6:在字符串中移动单词
【发布时间】:2018-05-14 19:13:06
【问题描述】:

我知道这个函数会围绕字符串中的字符移动,例如:

def swapping(a, b, c):
    x = list(a)
    x[b], x[c] = x[c], x[b]
    return ''.join(x)

这让我可以这样做:

swapping('abcde', 1, 3)
'adcbe'
swapping('abcde', 0, 1)
'bacde'

但是我怎样才能让它做这样的事情,所以我不只是在字母周围移动?这就是我想要完成的:

swapping("Boys and girls left the school.", "boys", "girls")
swapping("Boys and girls left the school.", "GIRLS", "bOYS")
should both have an output: "GIRLS and BOYS left the school." 
# Basically swapping the words that are typed out after writing down a string

【问题讨论】:

  • @DeepSpace,不太像……
  • 如果出现多次怎么办?

标签: python python-3.x


【解决方案1】:

你可以这样做:

def swap(word_string, word1, word2):
    words = word_string.split()
    try:
        idx1 = words.index(word1)
        idx2 = words.index(word2)
        words[idx1], words[idx2] = words[idx2],words[idx1]
    except ValueError:
        pass
    return ' '.join(words)

【讨论】:

  • 广泛的except: 是不好的做法,甚至在PEP 8 中也是如此
  • 你还有错别字,除了大写
  • 非常感谢,@OlivierMelançon 我的错。已编辑。
  • 你可以pass以防出现异常,这样你就只有一个return ' '.join声明,因为无论如何你都在这样做。
【解决方案2】:

使用正则表达式和替换函数(可以使用 lambda 和双三进制来完成,但这不是真正可读的)

匹配所有单词 (\w+) 并与两个单词进行比较(不区分大小写)。如果找到,返回“相反”字。

import re

def swapping(a,b,c):
    def matchfunc(m):
        g = m.group(1).lower()
        if g == c.lower():
            return b.upper()
        elif g == b.lower():
            return c.upper()
        else:
            return m.group(1)

    return re.sub("(\w+)",matchfunc,a)

print(swapping("Boys and girls left the school.", "boys", "girls"))
print(swapping("Boys and girls left the school.", "GIRLS", "bOYS"))

都打印:GIRLS and BOYS left the school.

【讨论】:

  • 这个给了我想要的输出,谢谢。快速提问:产生这个输出是否有必要?我还没有完全学会。
【解决方案3】:

使用split函数获取以whitespaces分隔的单词列表

def swapping(a, b, c):
x = a.split(" ")
x[b], x[c] = x[c], x[b]
return ' '.join(x)

如果您想将字符串作为参数传递,请使用.index() 来获取您要交换的字符串的索引。

def swapping(a, b, c):
x = a.split(" ")
index_1 = x.index(b)
index_2 = x.index(c)
x[index_2], x[index_1] = x[index_1], x[index_2]
return ' '.join(x)

【讨论】:

    【解决方案4】:

    您想在这里做两件事:交换和更改字符大小写。

    前者已在其他答案中解决。

    后者可以通过以不区分大小写的方式搜索单词来完成,但替换为输入的单词,保持大小写。

    def swapping(word_string, word1, word2):
        # Get list of lowercase words
        lower_words = word_string.lower().split()
    
        try:
            # Get case insensitive index of words
            idx1 = lower_words.index(word1.lower())
            idx2 = lower_words.index(word2.lower())
        except ValueError:
            # Return the same string if a word was not found
            return word_string
    
        # Replace words with the input words, keeping case
        words = word_string.split()
        words[idx1], words[idx2] = word2, word1
    
        return ' '.join(words)
    
    swapping("Boys and girls left the school.", "GIRLS", "BOYS")
    # Output: 'GIRLS and BOYS left the school.'
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-11-04
      • 1970-01-01
      • 2018-10-15
      • 1970-01-01
      • 1970-01-01
      • 2017-04-12
      • 1970-01-01
      • 2013-01-10
      相关资源
      最近更新 更多