Python 3.6:在字符串中移动单词
我知道该函数在字符串中围绕字符移动,例如:Python 3.6:在字符串中移动单词,python,python-3.x,Python,Python 3.x,我知道该函数在字符串中围绕字符移动,例如: 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 g
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
使用
split
函数获取由空格分隔的单词列表
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)
您可以这样做:
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)
在这里,您需要做两件独立的事情:交换和更改字符大小写 前者已在其他答复中提到 后者可以通过不区分大小写的方式搜索单词,但替换为输入单词,保留大小写
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.'
使用正则表达式和替换函数(可以使用
lambda
和双三元函数完成,但这不是真正可读的)
匹配所有单词(\w+
),并与这两个单词进行比较(不区分大小写)。如果找到,则返回“相反”单词
两个印刷体:
女孩和男孩都离开了学校。
@DeepSpace,不是真的那样……如果有多次发生呢?广泛的除了:
是不好的做法,甚至在你仍然有一个打字错误,除了大写的汉克一吨,@OlivierMelanç在我的坏习惯上。已编辑。如果出现异常,您可以传递
,这样您就只有一个返回“”。加入
语句,因为无论发生什么情况,您都要这样做。这条语句为我提供了所需的输出,谢谢。快速提问:生成此输出是否需要“re”?我还没完全学会。
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"))