替换某个索引中的字符 [英] Replacing a character from a certain index
问题描述
如何替换来自某个索引的字符串中的字符?比如我想从一个字符串中获取中间的字符,比如abc,如果这个字符不等于用户指定的字符,那么我想替换它.
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.
可能是这样的吗?
middle = ? # (I don't know how to get the middle of a string)
if str[middle] != char:
str[middle].replace('')
推荐答案
因为字符串是 不可变在 Python 中,只需创建一个新字符串,其中包含所需索引处的值.
As strings are immutable in Python, just create a new string which includes the value at the desired index.
假设你有一个字符串 s
,也许 s = "mystring"
Assuming you have a string s
, perhaps 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:]
您可以通过将字符串长度除以 2 来找到中间值 len(s)/2
You can find the middle by dividing your string length by 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:]
这将作为
replacer("mystring", "12", 4)
'myst12ing'
这篇关于替换某个索引中的字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!