let's say i have list
strs = ["dog","racecar","car"]
when I = 0 , then I want
d,r,c
when I = 1, then I want
do,ra,ca
when I = 2, then I want
dog,rac,car
like that How can i do this ?
let's say i have list
strs = ["dog","racecar","car"]
when I = 0 , then I want
d,r,c
when I = 1, then I want
do,ra,ca
when I = 2, then I want
dog,rac,car
like that How can i do this ?
strs = ["dog","racecar","car"]
l = 0
for a in strs:
print(a[:l+1],end=' ')
Output
d r c
l
index, I use l+1
because the end is excluded.print('hello'[0:3])
it will give all strings to the index 0
to 2
not 3
/end=' '
so it will not ends with a new line.strs = ["dog","racecar","car"]
l = 0
lst = [a[:l+1] for a in strs]
print(*lst) # here *lst is same as print(lst[0],lst[1],...,lst[n])
Output
d r c
strs = ["dog","racecar","car"]
for l in range(min(len(a) for a in strs)):
for s in strs:
print(s[:l+1],end=' ')
print()
Output
d r c
do ra ca
dog rac car
strs = ["dog","racecar","car"]
for l in range(min(len(a) for a in strs)):
print(*[s[:l+1] for s in strs])
Output
d r c
do ra ca
dog rac car
min(len(a) for a in strs)
len(a) for a in strs
) generates a list with the value as the length of the string inside the list.min(len(a) for a in strs)
returns the lowest number from the above list.I hope my explanation is clear. If not please ask me in the comments.
First you need to find the minimum length and then loop through each size up to that length.
strs = ["dog","racecar","car"]
for l in range(min(len(w) for w in strs)):
print(",".join(s[:l+1] for s in strs))
strs = ["dog","racecar","car"]
def func(arr,n):
w=""
for i in range(len(arr)):
if n<=len(arr[0])-1:
w+=(arr[i])[0:n]+" "
else:
w+=arr[i]+" "
return w;
print(func(strs,2))
Keep on adding sliced portions of each string via loops,If the value of "l" [the variable you used to refer to the final pos] were to exceed the length of the string, the string would be added as a whole. (at least that's how I would handle that case).