-2

I am trying to sort through an output of a command line, and I need to snip a certain name that can vary in length, and name. The output I am trying to split is

AP Name.......................................... AP-Test

The name AP-Test can be any length or name. I was trying to split it by, '.' but that would create a bunch of substrings. I currently store my output into a file called Result.txt, sort through looking for lines with AP Name, but I need to snag the end of the string stored in a list.


 APnames = []                       # AP name lists
 APlinenum = 0                # AP line number index
 APsubstr = "AP Name.".lower()                # searching for "AP Name".

 fileA = open("Results.txt", 'a+')
       for line in fileA:
           APlinenum += 1
           if line.lower().find(APsubstr) != -1:    # if case-insensitive match,
           APnames.append(line.rstrip('\n'))

       fileA.close()

APname = "the actual AP-name"



There is the issue of if the AP name contains a period, it would be split.

The expected output would be the string APname is the exact name and no other characters.

Matt
  • 35
  • 5
  • What is your expected output? – Nithin May 24 '19 at 17:27
  • "The name AP-Test can be any length or name". Can that name contain a period? – Kevin May 24 '19 at 17:29
  • The quality of the answer depends on how good you are able to specify what the lines look like and what you want to extract from it. For example, if the word is always on the 51st character of the line, than it's easy to remove the first 50 characters. If the separator is alwasy multiple consecutive periods, and the parts before and after it do not contain multiple consecutive periods, than you can use a regular expression. But if there can be periods anywhere in the line and the lenghths can also vary, then how would you know what/where the name is? – wovano May 24 '19 at 18:21

3 Answers3

0

Why not just count the dots and split by the result?

num_of_dots = txt.count('.')
txt.split('.'*num_of_dots)
Alec
  • 8,529
  • 8
  • 37
  • 63
0

You can use a regular expression to split by "at least one dot":

import re
print(re.split('\.+', APnames))

Here \. means a literal . (instead of "any character", which is what . usually means in regex), and + means "any number of times in a row, but at least once".

Example usage:

>>> re.split('\.+', 'a....b')
['a', 'b']
>>> re.split('\.+', 'a.......b')
['a', 'b']

If the strings themselves can contain dots, you could require more than one dot to do the split, by changing the regex to something like \.{3,} to require at least 3 dots.

Blorgbeard
  • 101,031
  • 48
  • 228
  • 272
0

Check out this: https://stackoverflow.com/a/15012237

string.rsplit('delimeter',1)[1]
Braeden Smith
  • 25
  • 1
  • 7