+ 5
How can I print this?
Suppose: x = "1a2bee3d4f" Output: 1a:2b:ee:3d:4f
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 ) ) )
+ 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)
+ 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))
+ 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)
+ 2
Thank you guys ☺️
+ 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))
+ 1
#beginner Code solution with Format could be considered for this fixed-len string ? Thanks for your feedback