我在程序的输出中得到了空格。你知道怎么摆脱他们吗?

2024-09-22 20:38:27 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在开发一个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

Tags: 字符串inforstringlen空间extractany
3条回答

请尝试以下操作:

extract = []
W = str(input("Please enter any string: "))
vowels = ['a','e','i','o','u']

for i in W:
    extract.append(i)
print(extract)

for i in range(len(W)):
    j = i + 1 
    if W[i] in vowels:
        while j <= len(W):
            X = W[i:j]
            j += 1
            print(X)

打印这些新行的原因是因为您正在打印空字符串;想想每个ij是什么

例如,当i可能是3时,可以将j重置回1。而且{}是{}

要回答这个问题,为什么要获得空格,这个修改后的代码版本应该可以帮助您理解。 您可以看到在获得W[3:2]=''等切片的值时生成的空格 我不知道为什么要将字符串的列表版本设置为“extract”,而不使用它

vowels = ['a','e','i','o','u']

W = 'somestring'

j = 1
for i in range(len(W)):
    if W[i] in vowels:
        while j <= len(W):
            X = W[i:j]
            j += 1
            print(f"W[{i}:{j}] is Substring: {X}")
    j = 1
W[1:2] is Substring: 
W[1:3] is Substring: o
W[1:4] is Substring: om
W[1:5] is Substring: ome
W[1:6] is Substring: omes
W[1:7] is Substring: omest
W[1:8] is Substring: omestr
W[1:9] is Substring: omestri
W[1:10] is Substring: omestrin
W[1:11] is Substring: omestring
W[3:2] is Substring: 
W[3:3] is Substring: 
W[3:4] is Substring: 
W[3:5] is Substring: e
W[3:6] is Substring: es
W[3:7] is Substring: est
W[3:8] is Substring: estr
W[3:9] is Substring: estri
W[3:10] is Substring: estrin
W[3:11] is Substring: estring
W[7:2] is Substring: 
W[7:3] is Substring: 
W[7:4] is Substring: 
W[7:5] is Substring: 
W[7:6] is Substring: 
W[7:7] is Substring: 
W[7:8] is Substring: 
W[7:9] is Substring: i
W[7:10] is Substring: in
W[7:11] is Substring: ing

您可以将python字符串的终止字符修改为null,并且仅在X存在时打印新行字符

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
            # Here are the changes
            print(X, end="") #add end=""
            if X != "":
                print() #print new line when x exists
    j = 1

相关问题 更多 >