简体   繁体   中英

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. so for example, 000000020000000050000000190000000200000000 should equal "test". Sorry, I am very new to python and am not good. 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()

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. 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).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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