1

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 ?

3 Answers3

2

First Part

1.

strs = ["dog","racecar","car"]

l = 0
for a in strs:
    print(a[:l+1],end=' ')

Output

d r c 

Explanation.

  1. First loop through all the strings in the list.
  2. Then print the string only to the l index, I use l+1 because the end is excluded.
  3. Means If you run print('hello'[0:3]) it will give all strings to the index 0 to 2 not 3/
  4. 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)

  1. Here inner comprehension(len(a) for a in strs) generates a list with the value as the length of the string inside the list.
  2. 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.

codester_09
  • 5,622
  • 2
  • 5
  • 27
  • I want to iterate in the range of min value in the list here let's say dog or car, so next time iteration it should return me 2 characters and then 3 character till min item length – Prajapati Yash Oct 02 '22 at 17:58
  • 1
    Instead of `l = 0`, you could generate `l` with `for l in range(min(len(w) for w in strs)):` – tdelaney Oct 02 '22 at 18:01
  • @PrajapatiYash Can you explain to me or can you give some samples of input and output? – codester_09 Oct 02 '22 at 18:01
0

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))
tdelaney
  • 73,364
  • 6
  • 83
  • 116
0
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).