Search code examples
pythonarrayslistclipboardpywin32

How to split a string at line breaks in python?


I want to copy some tabular data from Excel into a python array. That is, user willselect a range in an Excel table, press "Copy" (CTRL+C) so that the range will be copied to clipboard. Then I will get this clipboard data into a python array (list). I use win32clipboard from pywin32 to get clipboard data into an array:

import win32clipboard

def getClip():
    win32clipboard.OpenClipboard()
    data = win32clipboard.GetClipboardData()
    win32clipboard.CloseClipboard()
    return data

I copy the following range A1:B5 from Excel:

enter image description here

When I use the function above, I get a string like:

'365\t179\r\n96\t-90\r\n48\t-138\r\n12\t-174\r\n30\t-156\r\n'

How to split this string into a list, so that the list will look like:

[(365,179), (96, -90), (48, -138), (12, -174), (30, -156)]

I use split method, but it doesn't give me what I want.

data.split("\n")

['365\t179\r', '96\t-90\r', '48\t-138\r', '12\t-174\r', '30\t-156\r', '']

Solution

  • >>> s = '365\t179\r\n96\t-90\r\n48\t-138\r\n12\t-174\r\n30\t-156\r\n'
    >>> [map(int, x.split('\t')) for x in s.rstrip().split('\r\n')]
    [[365, 179], [96, -90], [48, -138], [12, -174], [30, -156]]
    

    Using the code from my other answer, you can also handle other types as well:

    from ast import literal_eval
    def solve(x):
        try:
            return literal_eval(x)
        except (ValueError, SyntaxError):
            return x
    
    s = '365\tFoo\r\nBar\t-90.01\r\n48\tspam\r\n12e10\t-174\r\n30\t-156\r\n'
    print [map(solve, x.split('\t')) for x in s.rstrip().split('\r\n')]
    #[[365, 'Foo'], ['Bar', -90.01], [48, 'spam'], [120000000000.0, -174], [30, -156]]