+ 5

How can I print this?

Suppose: x = "1a2bee3d4f" Output: 1a:2b:ee:3d:4f

30th May 2022, 9:51 AM
Fꫀⲅძ᥆͟ᥙ᥉᯽
Fꫀⲅძ᥆͟ᥙ᥉᯽ - avatar
8 Antworten
+ 4
If you can be sure the string length was always even, you can slice each 2 characters of the string using ranged for...in loop, and then join the result to string using colon as delimiter. x = "1a2bee3d4f" print( ":".join( x[ pos : pos + 2 ] for pos in range( 0, len( x ), 2 ) ) )
30th May 2022, 10:56 AM
Ipang
+ 5
Try this simple code. x = "1a2bee3d4f" out_put = "" for i in range(0, len(x)): out_put += x[i ] if i % 2 != 0 and i != len(x) - 1: out_put += ":" print(out_put)
30th May 2022, 10:10 AM
Christian Fare T.
Christian Fare T. - avatar
+ 5
MD. Ferdous Ibne Abu Bakar , here is a version with a basic for loop: txt = "1a2bee3d4f" chunk_size = 2 chunk_lst = [] for i in range(0, len(txt), chunk_size): chunk_lst.append(txt[i:i+chunk_size]) print(":".join(chunk_lst))
30th May 2022, 7:18 PM
Lothar
Lothar - avatar
+ 3
Other solution: x = "1a2bee3d4f" out='' for c, v in enumerate(x): out+=v if c%2!=0 or c==0 else ':'+v print(out)
1st Jun 2022, 1:06 AM
Monica Garcia
Monica Garcia - avatar
+ 2
Thank you guys ☺️
30th May 2022, 10:51 AM
Fꫀⲅძ᥆͟ᥙ᥉᯽
Fꫀⲅძ᥆͟ᥙ᥉᯽ - avatar
+ 2
MD. Ferdous Ibne Abu Bakar you can make a generic function for this. Basically Lothar's solution wrapped into a function. x = "1a2bee3d4f" def sep_by_n(s, n=2, sep=":"): return sep.join([(s[i:i+n]) for i in range(0, len(s), n)]) #Test #default by 2, sep=":" print(sep_by_n(x)) #change sep print(sep_by_n(x, sep=" <-> ")) #change n print(sep_by_n(x, 1)) print(sep_by_n(x, 3)) print(sep_by_n(x, 4))
1st Jun 2022, 7:46 AM
Bob_Li
Bob_Li - avatar
+ 1
#beginner Code solution with Format could be considered for this fixed-len string ? Thanks for your feedback
31st May 2022, 1:59 PM
Philippe Kolaczek
Philippe Kolaczek - avatar