Search code examples
pythonstringinsertiondd

Extracting a changeable string from a list and insertion in Python


I have a list that looks like this:

['2    19   2839475239874 hda']

I need to extract the hda from the end. However, the hda may not always be the last chunk, hda may not always be only 3 letters (it could be 4 or 5, and it could include numbers); BUT it will always start with the letter 'h'.

After the hda is successfully extracted, I then need to insert that chunk into a dd command. That looks like this:

dd if=/dev/zero of=/dev/hda bs=512 count=1

But if the hda could be different each time I run the dd command, I need a way to have the 'hda' part of the dd command changeable.

Sorry if this is confusing, I am a beginner and confused myself! I've tried using startswith for extraction, but can't even get past there!


Solution

  • Simply like so:

    lst = ['2    19   2839475239874 hda']
    
    # Extracting the device part
    dev = filter(lambda s: s[0] is 'h', lst[0].split())[0]
    
    # Inserting it
    cmd = 'dd if=/dev/zero of=/dev/{0} bs=512 count=1'.format(dev)
    

    You will want to check the case where you don't have any h-word in your list though.