Python 替换某个索引中的字符

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/41752946/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-20 01:33:53  来源:igfitidea点击:

Replacing a character from a certain index

pythonpython-3.xstring

提问by Jordan Baron

How can I replace a character in a string from a certain index? For example, I want to get the middle character from a string, like abc, and if the character is not equal to the character the user specifies, then I want to replace it.

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

Something like this maybe?

也许像这样的东西?

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

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

回答by ti7

As strings are immutablein Python, just create a new string which includes the value at the desired index.

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

Assuming you have a string s, perhaps s = "mystring"

假设你有一个字符串s,也许s = "mystring"

You can quickly (and obviously) replace a portion at a desired index by placing it between "slices" of the original.

您可以通过将其放置在原始“切片”之间来快速(并且显然)替换所需索引处的部分。

s = s[:index] + newstring + s[index + 1:]

You can find the middle by dividing your string length by 2 len(s)/2

您可以通过将字符串长度除以 2 来找到中间值 len(s)/2

If you're getting mystery inputs, you should take care to handle indices outside the expected range

如果您收到神秘输入,则应注意处理超出预期范围的索引

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

This will work as

这将作为

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

回答by Willem Van Onsem

Strings in Python are immutablemeaning you cannot replaceparts of them.

Python 中的字符串是不可变的,这意味着您无法替换它们的一部分。

You can however create a new stringthat is modified. Mind that this is not semantically equivalentsince other references to the old string will not be updated.

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

You could for instance write a function:

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

def replace_str_index(text,index=0,replacement=''):
    return '%s%s%s'%(text[:index],replacement,text[index+1:])

And then for instance call it with:

然后例如调用它:

new_string = replace_str_index(old_string,middle)

If you do not feed a replacement, the new string will not contain the character you want to remove, you can feed it a string of arbitrary length.

如果不提供替换,新字符串将不包含要删除的字符,您可以提供任意长度的字符串。

For instance:

例如:

replace_str_index('hello?bye',5)

will return 'hellobye'; and:

会回来'hellobye';和:

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

will return 'hellogoodbye'.

会回来'hellogoodbye'

回答by Jacob Malachowski

You can't replace a letter in a string. Convert the string to a list, replace the letter, and convert it back to a string.

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

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

回答by Shivam Bharadwaj

# 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 : The cat sat on the mat

I/P : 猫坐在垫子上

O/P : The cat slept on the mat

O/P : 猫睡在垫子上