MathEnthusiast
MathEnthusiast

Reputation: 11

Why does this code for a list fail for large entries?

I am writing a code for a cipher and I want to turn one-digit numbers to two-digit numbers with 0 at the front of them.

I want to turn a list like this:

[":","2",":","3",":","4",":"]

to this:

[":", "0","2", ":", "0","3". ":", "0","4",":"]

But I don't get why my code fails when the list gets large. Here's my code:

text = str(input("Enter the text you want to encode: "))
text = ':' + text + ':'

n = len(text)
text = list(text)
t_test = text

for i in range(2,n):
    if text[i] == ':' and text[i-2] == ":":
        t_test.insert((i-1),"0")
t_test = text
print(text)

for example when I input this:

1:2:3:4:5:6

it fails to insert a zero in front of the 5 and 6. It outputs this:

[':', '0', '1', ':', '0', '2', ':', '0', '3', ':', '0', '4', ':', '5', ':', '6', ':']

instead of:

[':', '0', '1', ':', '0', '2', ':', '0', '3', ':', '0', '4', ':', '0', '5', ':', '0', '6', ':']

I have tried for smaller entries and it works, but I don't know why it starts to fail at some point.

Upvotes: 1

Views: 76

Answers (3)

Red
Red

Reputation: 27557

For one, the code you posted doesn't work for any entry, big or small. Here is how I used a list comprehension to convert a list like your example showed:

l = [":","2",":","3",":","4",":"]
l = [a for b in [["0",i] if i.isdigit() else [i] for i in l] for a in b]
print(l)

Output:

[':', '0', '2', ':', '0', '3', ':', '0', '4', ':']

Here's another way:

l = [":","2",":","3",":","4",":"]
l = ' '.join([f"0 {i}" if i.isdigit() else i for i in l]).split()
print(l)

Output:

[':', '0', '2', ':', '0', '3', ':', '0', '4', ':']

Upvotes: 0

revliscano
revliscano

Reputation: 2272

Another way, just in case you don't want to use regular expressions. Here we use (basically) only methods of the str class and a list comprehension.

text = '1:2:3:4:5:6'
list_ = text.split(':')
format_number = lambda x: f'0{x}' if x.isdigit() and len(x) == 1 else x
result = [* ':' + ":".join([format_number(str(x)) for x in list_]) + ':']

output for print(result):

[':', '0', '1', ':', '0', '2', ':', '0', '3', ':', '0', '4', ':', '0', '5', ':', '0', '6', ':']    

Upvotes: 0

Nick
Nick

Reputation: 147156

If you want to modify a string it might be better to stick with string functions. For example, you could use regex to find single digits and add a leading zero:

import re

text = '2:3:4:5:6:10:44'

t_test = re.sub(r'\b(\d)\b', r'0\1', ':' + text + ':')
print(t_test, list(t_test), sep="\n")

Output:

:02:03:04:05:06:10:44:
[':', '0', '2', ':', '0', '3', ':', '0', '4', ':', '0', '5', ':', '0', '6', ':', '1', '0', ':', '4', '4', ':']

Upvotes: 2

Related Questions