Trying to create a triangular print pattern for an input string caused the following problem. Here is the code:
string=input("Please enter your word: ")
printable=""
l=0
while l<len(string):
for i in string:
printable =i
print(printable)
l =1
q=0
while q!=len(string):
for z in string:
string=string.replace(string[-1],"")
if string=="":
break
print(string)
For an input containing only one word ("Python") it works fine and it prints out:
P
Py
Pyt
Pyth
Pytho
Python
Pytho
Pyth
Pyt
Py
P
The problem starts when a string with a space between the words is entered ("Elvis Presley"):
E
El
Elv
Elvi
Elvis
Elvis
Elvis P
Elvis Pr
Elvis Pre
Elvis Pres
Elvis Presl
Elvis Presle
Elvis Presley
Elvis Presle
Elvis Prsl
Evis Prs
Evi Pr
Evi P
Evi
Evi
Ev
E
Most probably it is because when it reaches back Pres"l" it also removes the "l" in Elvis. How can I fix that? Would be glad if you assist me. Thank you!
CodePudding user response:
This has nothing to do with multiple words, the problem is when there are duplicate characters in the string. string.replace(string[-1],"")
will remove all the occurrences of the last character. So when the last character is l
, it removes the l
in Elvis
as well.
Use a slice to remove the last character, not replace()
.
string = string[:-1]
CodePudding user response:
Actually it doesn't work with a single word string, too. if I enter "Banana" the output is:
B
Ba
Ban
Bana
Banan
Banana
Bnn
B
When the program reaches a repeating character it is being removed from everywhere.
CodePudding user response:
The problem is in your second loop string=string.replace(string[-1],"")
. If you replace the last character of string you replace all instances. So that 'Elvis Presle'.replace('e', '')
results in "Elvis Prsl"
.
Instead of replace
use indexing - string = string[:-1]
.
P.S. You can simplify looping through string like this:
while string:
string = string[:-1]
print(string)
CodePudding user response:
The problem is on
string=string.replace(string[-1],"")
It replace letters with nothing so when letter 'e' was found all of them are erased same as letter 'l'. You can use indexing instead of letters.
l=0
while l<len(string) 1:
print(string[:l])
l =1
It means that take letter by letter starting from the left to the right. Then you can use reverse of the slicing method. string[:-1] means that take until to the last letter.
l=1
while l<len(string) 1:
print(string[:l*-1])
l =1
Thus the entire code will be:
string=input("Please enter your word: ")
l=0
while l<len(string) 1:
print(string[:l])
l =1
l=1
while l<len(string) 1:
print(string[:l*-1])
l =1