python - Python 3.6:在字符串中移动单词
问题描述
我知道这个函数在字符串中的字符周围移动,例如:
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
解决方案
你可以这样做:
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)
推荐阅读
- c# - Unity C#:如何在动画组件中返回变量的列表/数组/长度?
- python - 什么时候应该使用 gevent(StreamServer) 与 ThreadingTCPServer?
- python - 使用不同的对象类型作为参数初始化 python 对象
- javascript - 如何在打字稿中正确使用泛型?
- c - “?”有什么用?和“:”在以指针为参数的函数中?
- c# - 检查字符串是否有任何列表
价值观 - tensorflow - Keras,ImageDataGenerator,无法识别图像文件
- java - 尝试在 java 1.6 中调用 bean 中的方法时视图层出错
- sql - SQL - 对数学表达式进行四舍五入
- php - Laravel 8、Passport 和 MongoDB 集成