Python exercise, guidance for slicing substrings

Question:

Please write a program which asks the user to type in a string. The program then prints out all the substrings which begin with the first character, from the shortest to the longest. Have a look at the example below.

Please type in a string: test
t
te
tes
test

Obviously my code is not the way it supposed to be:

stg = input("Please type in a string: ")

print(stg[0])
print(stg[0:5])
print(stg[0:10])
print(stg[10:50])
print(stg[:])
Asked By: User216345

||

Answers:

ok, this is a homework and I don’t give you the exact solution… but as some points:

  1. you have a string and want to print first 1 letter, first 2 letters and so on… so your range end must increase one by one…
  2. you don’t know about input length so you can’t use hard code and use a loop
  3. for loop you need to know about string length and use a builtin method for getting the length…

any question? ask it…

Answered By: MoRe
userString = input("Gimme String: ")
# Looping based on the given String
# Last Value is not included so you need to increment the value by one
for i in range(len(userString)):
    # Last Value is not included so you need to increment the value by one
    print(userString[:i+1])

#Alternative
for i in range(1,len(userString)+1):
    print(userString[:i])
Answered By: jack
stg = input("Please type in a string: ")
print("n".join([stg[0:i+1] for i in range (len(stg))]))

Output:

t
te
tes
test
Answered By: johann

Just use simple for loop

stg = 'test'
temp_str = ''
for i in range(len(stg)):
    temp_str = temp_str + stg[i]
    print(temp_str)
Answered By: Sanju Halder
input_str1 = input("Please type in a string: ")
i = 0
while i < len(input_str1):
    print(input_str1[0:i+1])
    i+=1
Answered By: Adam
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.