简体   繁体   中英

how to split a string with a “ ” delimiter?

i have a file that i created that contains counts bad ip addresses and and puts that count in front of the ip address like this:

      2 88.208.222.32
      3 162.209.53.127
      6 218.2.22.103
      6 218.2.22.117
    357 218.2.22.114
    462 222.186.62.23
    484 61.160.215.176
    566 60.169.74.204
    635 61.160.215.87
    659 61.160.215.64
    874 202.201.1.92
    899 61.160.215.209
    944 210.51.54.132

the tricky part is the spaces in front of the first field. basically my end goal is to make a loop that says "if field 1# is greater than 50, then....." im new to python but am used to bash so im trying to learn ways to do this in python.

i thought re.split(" ") would be a good option but am unsure how to remove the first spaces. any advice would be appreciated.

Use str.split without argument:

>>> '      6 218.2.22.103'.split()
['6', '218.2.22.103']

According to the documentation, if no argument (or None ) is given:

runs of consecutive whitespace are regarded as a single separator, and the result will contain no empty strings at the start or end if the string has leading or trailing whitespace.

Python actually has a built-in split that does this by default:

"2 88.208.222.32".split()
>>> [2, 88.208.222.32]

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM