Python 替换某个索引中的字符

Python 替换某个索引中的字符,python,python-3.x,string,Python,Python 3.x,String,如何替换某个索引中字符串中的字符?例如,我希望从字符串中获取中间字符,如abc,如果该字符不等于用户指定的字符,则我希望替换它 也许是这样的 middle = ? # (I don't know how to get the middle of a string) if str[middle] != char: str[middle].replace('') Python中的字符串是不可变的意思是不能替换它们的一部分 但是,您可以创建一个被修改的新字符串。请注意,这在语义上是不等价的

如何替换某个索引中字符串中的字符?例如,我希望从字符串中获取中间字符,如abc,如果该字符不等于用户指定的字符,则我希望替换它

也许是这样的

middle = ? # (I don't know how to get the middle of a string)

if str[middle] != char:
    str[middle].replace('')

Python中的字符串是不可变的意思是不能替换它们的一部分

但是,您可以创建一个被修改的新字符串。请注意,这在语义上是不等价的,因为对旧字符串的其他引用不会被更新

例如,您可以编写一个函数:

def replace_str_index(text,index=0,replacement=''):
    return '%s%s%s'%(text[:index],replacement,text[index+1:])
然后,例如,用以下方法调用它:

new_string = replace_str_index(old_string,middle)
如果不提供替换,则新字符串将不包含要删除的字符,可以提供任意长度的字符串

例如:

replace_str_index('hello?bye',5)
将返回“hellobye”;以及:

replace_str_index('hello?bye',5,'good')

将返回
'hellogoodbay'

您不能替换字符串中的字母。将字符串转换为列表,替换字母,然后将其转换回字符串

>>> s = list("Hello world")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'W', 'o', 'r', 'l', 'd']
>>> s[int(len(s) / 2)] = '-'
>>> s
['H', 'e', 'l', 'l', 'o', '-', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello-World'
由于字符串在Python中,只需创建一个新字符串,其中包含所需索引处的值

假设您有一个字符串
s
,可能是
s=“mystring”

通过将一部分放在原始的“切片”之间,可以快速(显然)替换所需索引处的一部分

s = s[:index] + newstring + s[index + 1:]
您可以通过将字符串长度除以2
len(s)/2

如果你得到的是神秘的输入,你应该注意处理超出预期范围的索引

def replacer(s, newstring, index, nofail=False):
    # raise an error if index is outside of the string
    if not nofail and index not in range(len(s)):
        raise ValueError("index outside given string")

    # if not erroring, but the index is still not in the correct range..
    if index < 0:  # add it to the beginning
        return newstring + s
    if index > len(s):  # add it to the end
        return s + newstring

    # insert the new string between "slices" of the original
    return s[:index] + newstring + s[index + 1:]
I/p:猫坐在垫子上


O/p:猫睡在垫子上

如果必须在特定索引之间替换字符串,也可以使用以下方法

def Replace_Substring_Between_Index(singleLine,stringToReplace='',startPos=0,endPos=1):
    try:
       singleLine = singleLine[:startPos]+stringToReplace+singleLine[endPos:]
    except Exception as e:
        exception="There is Exception at this step while calling replace_str_index method, Reason = " + str(e)
        BuiltIn.log_to_console(exception)
    return singleLine

它应该如何从该字符串中替换?字符串是不可变的,您需要创建一个新字符串。它的形式是
slice\u-before\u-index+char+slice\u-before\u-index
。。。这意味着您必须构建一个新的字符串,这是否回答了您的问题?请注意,您仍然没有修改字符串:您创建了一个新字符串。这是一个重要的细微差别。在尝试xrange函数上方的函数时,函数抛出了一个错误。有我们需要导入的库吗?哦,我要更新一下Python 2.7版的Python 3.x
range
# Use slicing to extract those parts of the original string to be kept
s = s[:position] + replacement + s[position+length_of_replaced:]

# Example: replace 'sat' with 'slept'
text = "The cat sat on the mat"
text = text[:8] + "slept" + text[11:]
def Replace_Substring_Between_Index(singleLine,stringToReplace='',startPos=0,endPos=1):
    try:
       singleLine = singleLine[:startPos]+stringToReplace+singleLine[endPos:]
    except Exception as e:
        exception="There is Exception at this step while calling replace_str_index method, Reason = " + str(e)
        BuiltIn.log_to_console(exception)
    return singleLine