替换某个索引

时间:2017-01-19 22:32:50

标签: 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('')

5 个答案:

答案 0 :(得分:15)

由于Python中的字符串是immutable,只需创建一个新字符串,其中包含所需索引处的值。

假设您有一个字符串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 xrange(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:]

这将作为

replacer("mystring", "12", 4)
'myst12ing'

答案 1 :(得分:9)

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')

将返回'hellogoodbye'

答案 2 :(得分:5)

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

>>> s = list("Hello world")
>>> s
['H', 'e', 'l', 'l', 'o', ' ', 'z', 'o', 'r', 'l', 'd']
>>> s[int(len(s) / 2)] = '-'
>>> s
['H', 'e', 'l', 'l', 'o', '-', 'W', 'o', 'r', 'l', 'd']
>>> "".join(s)
'Hello-World'

答案 3 :(得分:4)

# 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:]

I / P:猫坐在垫子上

O / P:猫睡在垫子上

答案 4 :(得分:-2)

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

pthread_setschedparam
相关问题