简体   繁体   English

如何在不使用 replace() 方法的情况下从字符串中删除特定元素?

[英]How do I remove specific elements from a string without using replace() method?

I'm trying to traverse through a string using its indices and remove specific elements.我正在尝试使用其索引遍历字符串并删除特定元素。 Due to string length getting shorter as elements are removed, it always goes out of range by the time the final element is reached.由于字符串长度随着元素的删除而变短,因此在到达最终元素时它总是超出范围。

Here's some code to ilustrate what I'm trying to do.这是一些代码来说明我正在尝试做的事情。 For example, going from "1.2.3.4" to "1234".例如,从“1.2.3.4”变为“1234”。

string = "1.2.3.4"
for i in range(len(string)):
    if string[i] == ".":
        string = string[:i] + string[i+1:]

I know there are alternate approaches like using string method called replace() and I can run string = string.replace(string[i], "", 1) OR I can traverse through individual elements (not indicies).我知道有替代方法,例如使用名为replace()的字符串方法,我可以运行string = string.replace(string[i], "", 1)或者我可以遍历单个元素(而不是索引)。

But how would I solve it using the approach above (traversing string indices)?但是我将如何使用上述方法(遍历字符串索引)来解决它? What techniques can I use to halt the loop after it reaches the final element of the string?在循环到达字符串的最后一个元素后,我可以使用哪些技术来停止循环? Without continuing to advance the index, which will go out of range as elements are removed earlier in the string.在不继续推进索引的情况下,这将使 go 超出范围,因为字符串中的元素已被删除。

Use this:用这个:

string = "1.2.3.4"
res = ""
for s in string: 
    if s != '.': 
        res += s

The result is of course '1234'.结果当然是“1234”。

it could be done like this (with a try/except block), but that's not really a great way to approach this problem (or any problem)可以这样完成(使用 try/except 块),但这并不是解决这个问题(或任何问题)的好方法

string = "1.2.3.4"


for i in range(len(string)):
    try:
        if string[i] == ".":
            string= string[:i]+string[i+1:]
    except:
        IndexError

result is 1234结果是1234

The only real change of course is that by adding a try/except around our loop, we save ourselves from the IndexError that would normally come up once we try to access an element in the string that is now out of bounds当然,唯一真正的变化是,通过在循环周围添加 try/except,我们将自己从 IndexError 中解救出来,一旦我们尝试访问字符串中现在超出范围的元素,通常会出现这种情况

Once that happens, the Exception is caught and we simply exit the loop with our finished string一旦发生这种情况,异常就会被捕获,我们只需使用完成的字符串退出循环

you can use the re module:你可以使用re模块:

import re
string = "1.2.3.4"
string = re.sub('\.','',string)
print(string)

If I understand correctly, you want to modify a string by its index while the length of it keep changing.如果我理解正确,您想通过其索引修改字符串,同时它的长度不断变化。

That's pretty dangerous.那是相当危险的。

The problem you ran into is caused by range(len(string)) .See, once the range is fixed, it won't change.And in the loop, string changes, it gets shorter, and that's why you got out of range error.你遇到的问题是由range(len(string))引起的。看,一旦range固定,它就不会改变。在循环中, string改变,它变得更短,这就是你超出范围的原因错误。

So what you want to do is to track the string while looping, and use if-else to find the '.'s, here is an example:因此,您要做的是在循环时跟踪string ,并使用if-else查找 '.',这是一个示例:

string = '1.2.3.4'
i = 0
while i < len(string):
    if string[i] == '.':
        string = string[:i] + string[i+1:]
    else:
        i += 1

Still, there are plenty of ways to deal with your string, don't use this, this is not good.不过,有很多方法可以处理你的字符串,不要使用这个,这不好。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何在不使用 .replace() 方法的情况下替换字符串中的单词,因为我希望该单词仅被删除一次 - How do I replace a word from a string without using .replace() method as I want the word to be removed only once 如何在不使用 remove() 或任何其他函数的情况下从列表中删除元素 - How do i remove elements from a list without using remove(), or any other functions 如何通过使用来自另一个数组的 pop 方法填充一个空数组的元素来“替换”一个数组? - How do i 'replace' an array by filling an empty array's elements using pop method from another array? 如何从列表中的某些字符串中删除特定字符串? - How do I remove a specific string from some strings in a list? 如何在不使用 .remove 的情况下从列表中删除元素 - How do I remove an element from a list without using .remove 如何删除字符串的特定部分? - How do I remove a specific part of a string? 如何删除XML元素而不删除元素尾部的内容? - How do I remove XML elements without removing content from the elements' tail? 如何从 python 中的 1 个字符串中删除特定案例元素 - how to remove specific case elements from 1 string in python 如何从字符串中删除 html 个元素,但使用正则表达式排除特定元素 - How to remove html elements from a string but exclude a specific element with regex 如何使用 Python 从 URL 中删除查询字符串 - How do I remove a query string from URL using Python
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM