简体   繁体   English

如何删除所有 7 个字符长的零 python

[英]how to remove all zeros that are 7 characters long python

I have made a string without spaces.我制作了一个没有空格的字符串。 so instead of spaces, I used 0000000. but there will be no alphabet letters.所以我用 0000000 代替了空格。但是不会有字母。 so for example, 000000020000000050000000190000000200000000 should equal "test".例如,000000020000000050000000190000000200000000 应该等于“测试”。 Sorry, I am very new to python and am not good.抱歉,我对 python 很陌生,而且不好。 so if someone can help me out, that would be awesome.所以如果有人可以帮助我,那就太棒了。

You should be able to achieve the desired effect using regular expressions and re.sub()您应该能够使用正则表达式和re.sub()达到预期的效果

If you want to extract the literal word "test" from that string as mentioned in the comments, you'll need to account for the fact that if you have 8 0 's, it will match the first 7 from left to right, so a number like 20 followed by 7 0 's would cause a few issues.如果您想从注释中提到的该字符串中提取文字“test”,您需要考虑这样一个事实,即如果您有 8 个0 ,它将从左到右匹配前 7 个,所以像20后跟 7 0这样的数字会导致一些问题。 We can get around this by matching the string in reverse (right to left) and then reversing the finished string to undo the initial reverse.我们可以通过反向匹配字符串(从右到左)然后反转完成的字符串以撤消初始反转来解决此问题。

Here's the solution I came up with as my revised answer:这是我作为修改后的答案提出的解决方案:

import re

my_string = '000000020000000050000000190000000200000000'

# Substitute a space in place of 7 0's
# Reverse the string in the input, and then reverse the output
new_string = re.sub('0{7}', ' ', my_string[::-1])[::-1]
# >>> new_string
# ' 20 5 19 20 '

Then we can strip the leading and trailing whitespace from this answer and split it into an array然后我们可以从这个答案中去除前导和尾随空格并将其拆分为一个数组

my_array = new_string.strip().split()
# >>> my_array
# ['20', '5', '19', '20']

After that, you can process the array in whatever way you see fit to get the word "test" out of it.之后,您可以以任何您认为合适的方式处理数组,以便从中提取“测试”一词。

My solution to that would probably be the following:我对此的解决方案可能如下:

import string

word = ''.join([string.ascii_lowercase[int(x) - 1] for x in my_array])
# >>> word
# 'test'

NOTE: This answer has been completely rewritten (v2).注意:此答案已完全重写(v2)。

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM