Python 查找字符串中的一对字符并将其替换为该字符串中的另一对字符
我不熟悉Python,但想知道如何获取字符串并交换字符对。假设我们有绳子 “HELLO\uuuuuuuuuuuuuuuuuuuuworld”并想在HELLO with\uuuuuuuuuuuuuuuu中切换HE。所以字符串现在看起来像“\uuuu LLOHEWORLD”怎么可能呢?它是否与.pop和.append有关?或者,如果可以使用elif,else函数?也许首先需要.index来查找用户指定需要交换的字符 我真的不知道从哪里开始 检查字符串方法:Python 查找字符串中的一对字符并将其替换为该字符串中的另一对字符,python,string,python-3.x,swap,Python,String,Python 3.x,Swap,我不熟悉Python,但想知道如何获取字符串并交换字符对。假设我们有绳子 “HELLO\uuuuuuuuuuuuuuuuuuuuworld”并想在HELLO with\uuuuuuuuuuuuuuuu中切换HE。所以字符串现在看起来像“\uuuu LLOHEWORLD”怎么可能呢?它是否与.pop和.append有关?或者,如果可以使用elif,else函数?也许首先需要.index来查找用户指定需要交换的字符 我真的不知道从哪里开始 检查字符串方法: s = 'HELLO__WORLD' s
s = 'HELLO__WORLD'
s = s.replace('HE', '__')
检查字符串方法:
s = 'HELLO__WORLD'
s = s.replace('HE', '__')
.pop()
和.append()
是列表
方法
阅读列表和数据结构
您可以使用replace
例如
.pop()
和.append()
是列表
方法
阅读列表和数据结构
您可以使用replace
例如
如其他答案中所述,这绝对是您想要使用的:
my_string = "HELLO__WORLD"
replaced = my_string.replace("HE","__")
print(replaced) #shows __LLO__WORLD
尽管如果字符串中的其他位置存在“HE”
且不应替换,这可能还不够:
my_string = "HE SAID HELLO_WORLD"
replaced = my_string.replace("HE","__")
print(replaced) #shows __ SAID __LLO_WORLD
在这种情况下,您需要指定要替换的整个零件:
my_string = "HE SAID HELLO_WORLD"
replaced = my_string.replace("HELLO_WORLD","__LLO__WORLD")
print(replaced) #shows HE SAID __LLO_WORLD
如其他答案中所述,这绝对是您想要使用的:
my_string = "HELLO__WORLD"
replaced = my_string.replace("HE","__")
print(replaced) #shows __LLO__WORLD
尽管如果字符串中的其他位置存在“HE”
且不应替换,这可能还不够:
my_string = "HE SAID HELLO_WORLD"
replaced = my_string.replace("HE","__")
print(replaced) #shows __ SAID __LLO_WORLD
在这种情况下,您需要指定要替换的整个零件:
my_string = "HE SAID HELLO_WORLD"
replaced = my_string.replace("HELLO_WORLD","__LLO__WORLD")
print(replaced) #shows HE SAID __LLO_WORLD
如果有要交换的子字符串的索引,可以将字符串转换为list,使用slice交换,然后将其转换回string
s = "HELLO__WORLD"
# "HE" is at [0:2], "__" is at [5:7]
s = list(s)
s[0:2], s[5:7] = s[5:7], s[0:2]
s = "".join(s)
print(s) # prints __LLOHEWORLD
要查找子字符串的索引,可以使用。查找:
s = "HELLO__WORLD"
s.find("__") #returns 5
如果有要交换的子字符串的索引,可以将字符串转换为list,使用slice交换,然后将其转换回string
s = "HELLO__WORLD"
# "HE" is at [0:2], "__" is at [5:7]
s = list(s)
s[0:2], s[5:7] = s[5:7], s[0:2]
s = "".join(s)
print(s) # prints __LLOHEWORLD
要查找子字符串的索引,可以使用。查找:
s = "HELLO__WORLD"
s.find("__") #returns 5
string.replace(“他”、“你”)或string.replace(“你好世界”、“你世界”)
string.replace(“他”、“你”)或string.replace(“你好世界”、“你世界”)
如果我将字符串转换为列表怎么办?那么我可以使用.pop()和.append()吗?可以。如果将字符串强制转换为列表,则可以使用.pop()和.append()。但我该如何执行此操作?如果将字符串转换为列表会怎么样?那么我可以使用.pop()和.append()吗?可以。如果您将字符串转换为一个列表,您可以使用.pop()和.append()。但是我该怎么做呢?谢谢迈尔斯,这真的很有帮助。谢谢迈尔斯,这真的很有帮助。