打印在字符串中找到的字符

时间:2016-03-03 22:33:11

标签: python string python-3.x find

直截了当:我想在字符串中打印这些字符的每个实例。例如:


    // *********************************************************************//
    // Interface: _IDTExtensibility2
    // Flags:     (4432) Hidden Dual OleAutomation Dispatchable
    // GUID:      {B65AD801-ABAF-11D0-BB8B-00A0C90F2744}
    // *********************************************************************//
      _IDTExtensibility2 = interface(IDispatch)
        ['{B65AD801-ABAF-11D0-BB8B-00A0C90F2744}']
        procedure OnConnection(const Application: IDispatch; ConnectMode: ext_ConnectMode; 
                               const AddInInst: IDispatch; var custom: PSafeArray); safecall;
        procedure OnDisconnection(RemoveMode: ext_DisconnectMode; var custom: PSafeArray); safecall;
        procedure OnAddInsUpdate(var custom: PSafeArray); safecall;
        procedure OnStartupComplete(var custom: PSafeArray); safecall;
        procedure OnBeginShutdown(var custom: PSafeArray); safecall;
      end;

会吐出来 CADA
* #Pseudocode below animals = 'cat dog fish goat pig' if 'abcd' in animals, print(instanceOfIt) catdog中的字母 我怎么做到这一点?

1 个答案:

答案 0 :(得分:1)

如果我理解正确的话:

animals = 'cat dog fish goat pig'
print(''.join(filter(lambda x: x in 'abcd', animals)))

filter接受一个函数和一个iterable,并返回一个新的iterable,它只包含那些函数返回的东西。

一个lambda表达式就像一个内联函数,它等同于在那里写myfunction并像之前那样定义它:

def myfunction(x):
    return x in 'abcd'

print(''.join(filter(myfunction, animals)))

另外(谢谢Peter Wood):

print(''.join(filter('abcd'.__contains__, animals)))