【问题标题】:Replacing a character from a certain index [duplicate]从某个索引替换字符[重复]
【发布时间】:2017-06-04 19:27:12
【问题描述】:

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

可能是这样的吗?

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

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

【问题讨论】:

标签: python python-3.x string


【解决方案1】:

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

【讨论】:

  • xrange 函数上方尝试您的函数时抛出错误。有没有我们需要导入的库?
  • 哦,我来更新一下xrange是Python 2.7版本的Python 3.x的range
  • @jeffhale 这个动作对于阅读这里的代码的人来说是显而易见的,一般来说不一定是显而易见的/作为一种可能的实现!
  • @ti7 我认为 Eric Blackman 在这篇 Nature 文章中解释了避免这种语言的最佳理由:nature.com/articles/550457e科技写作中的“明显”和“清楚地”这两个词。这些词在很大程度上没有帮助,尤其是对学生来说,如果所描述的内容实际上对他们来说并不明显或清楚,他们可能会适得其反。即使是最精明的读者也可能不同意关于什么是清楚和明显的。” ...
【解决方案2】:

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

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

【讨论】:

  • 请注意,您还没有修改字符串:您创建了一个新字符串。这是一个重要的细微差别。
【解决方案3】:

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'

【讨论】:

    【解决方案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 : 猫睡在垫子上

    【讨论】:

      【解决方案5】:

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

      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
      

      【讨论】:

        猜你喜欢
        • 2012-02-15
        • 1970-01-01
        • 2020-12-24
        • 1970-01-01
        • 2014-03-31
        • 1970-01-01
        • 1970-01-01
        • 2018-07-18
        • 1970-01-01
        相关资源
        最近更新 更多