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 ?
CodePudding user response:
First Part
1.
strs = ["dog","racecar","car"]
l = 0
for a in strs:
print(a[:l 1],end=' ')
Output
d r c
Explanation.
- First loop through all the strings in the list.
- Then print the string only to the
l
index, I usel 1
because the end is excluded. - Means If you run
print('hello'[0:3])
it will give all strings to the index0
to2
not3
/ - set
end=' '
so it will not ends with a new line.
2.
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
Second part
1.
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
2.
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
Explanation for min(len(a) for a in strs)
- Here inner comprehension(
len(a) for a in strs
) generates a list with the value as the length of the string inside the list. - Then
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.
CodePudding user response:
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))
CodePudding user response:
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).