Warning: file_get_contents(/data/phpspider/zhask/data//catemap/4/string/5.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181

Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/python-3.x/17.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
String 如何测试字母在字符串中的索引,并使用它替换另一个字符串的部分?_String_Python 3.x_Replace - Fatal编程技术网

String 如何测试字母在字符串中的索引,并使用它替换另一个字符串的部分?

String 如何测试字母在字符串中的索引,并使用它替换另一个字符串的部分?,string,python-3.x,replace,String,Python 3.x,Replace,因此,我会让用户输入一个字母,然后我还可以测试该字母是否在某个单词中。然而,我的目标是获取单词中字母的索引,例如,如果用户输入“e”,而我的单词是“great”,那么它将输出“2”。此外,我想使用此信息用与字母相同的索引替换另一个字符串的部分。像hangman一样,如果输出是“2”,那么假设我有另一个字符串“balloon”或“****”,我想用“e”替换第一个“l”或相应的“*”(第二个索引)。Python字符串是不可变的,所以我们需要将它们作为列表使用 >>> string

因此,我会让用户输入一个字母,然后我还可以测试该字母是否在某个单词中。然而,我的目标是获取单词中字母的索引,例如,如果用户输入“e”,而我的单词是“great”,那么它将输出“2”。此外,我想使用此信息用与字母相同的索引替换另一个字符串的部分。像hangman一样,如果输出是“2”,那么假设我有另一个字符串“balloon”或“****”,我想用“e”替换第一个“l”或相应的“*”(第二个索引)。

Python字符串是不可变的,所以我们需要将它们作为列表使用

>>> string1 = "great"
>>> string2 = "balloon"
>>> char = "e"
>>> string2 = list(string2)
>>> string2[string1.index(char)] = char
>>> string2
['b', 'a', 'e', 'l', 'o', 'o', 'n']
>>> string2 = ''.join(string2)
'baeloon'

字符串只是字符数组,所以只需使用
index()
方法。@“Bob the Berserking Bear”如果您可以添加一些您尝试过的代码片段以及一些示例输入和输出,它将帮助我们准确了解您尝试实现的目标。阅读这个问题,我不确定是否有2、3或4个字符串被操纵。