我正在开发一个python程序,它可以打印字符串的子字符串,但是要打印的子字符串是以元音开头的。我已经应用了逻辑,但是我得到了输出中不需要的空间。任何帮助都将不胜感激。以下是我的代码:
extract = []
W = str(input("Please enter any string: "))
vowels = ['a','e','i','o','u']
for i in W:
extract.append(i)
print(extract)
j = 1
for i in range(len(W)):
if W[i] in vowels:
while j <= len(W):
X = W[i:j]
j += 1
print(X)
j = 1
下面是我输入的字符串的输出:“somestring”
Please enter any string: somestring
['s', 'o', 'm', 'e', 's', 't', 'r', 'i', 'n', 'g']
o
om
ome
omes
omest
omestr
omestri
omestrin
omestring
e
es
est
estr
estri
estrin
estring
i
in
ing
看到我说的空间了吗?我不需要它们。我的输出应该类似于:
o
om
ome
omes
omest
omestr
omestri
omestrin
omestring
e
es
est
estr
estri
estrin
estring
i
in
ing
请尝试以下操作:
打印这些新行的原因是因为您正在打印空字符串;想想每个
i
的j
是什么例如,当}是{}
i
可能是3时,可以将j
重置回1。而且{要回答这个问题,为什么要获得空格,这个修改后的代码版本应该可以帮助您理解。 您可以看到在获得W[3:2]=''等切片的值时生成的空格 我不知道为什么要将字符串的列表版本设置为“extract”,而不使用它
您可以将python字符串的终止字符修改为null,并且仅在X存在时打印新行字符
相关问题 更多 >
编程相关推荐