在Python中打印字符串的一部分而跳过其他部分

2024-06-16 08:08:31 发布

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

假设我有以下代码:

myVariable = "goodmorning"

我可以用myVariable[1:2](就像Paolo Bergantino在这里说的:Is there a way to substring a string in Python?)来切分它,但是如何在跳过其他字符的同时打印一些字符呢?e、 g.如何使其打印“gdorn”?我试过myVariable[0,3,5,6,7](结果是错的),我在想,如果myVariable[0,3,5,6,7]有效,那么myVariable[0,3,5:7]可能也会有效(我希望你能看到我的推理),但事实并非如此。我是通过codecademy学习Python的,我还没有涉及函数,以防你涉及函数,如果有的话如果你能解释一下,我会很感激的!你知道吗


Tags: to函数代码instringissubstring字符
3条回答
my_indices = [1,2,5,6,9]
print "".join(x for i,x in enumerate(my_string) if i in my_indices)

你可以这样做吗

你也可以用numpy

print "".join(numpy.array(list(my_string))[my_indices])

这会让你做一些奇怪的事情,比如

my_indices = [1,2,3,4,9,9,8]

它可以简单到

myVariable = "goodmorning"
print (myVariable[0] + myVariable[3] + myVariable[5]  + myVariable[6] + myVariable[7] )

输出“gdorn”。你知道吗

它不优雅。它只是一次构建一个子字符串。你知道吗

你可以试试

myVariable = 'iheoiahwd'
idxs = [0, 3, 4, 6, 7]

myVariable = [myVariable[i] for i in idxs] 
print ''.join(myVariable)

或简化为一行:

print ''.join([myVariable[i] for i in [0, 3, 4, 6, 7]])

相关问题 更多 >