0

I am trying to set a variable equal to the last 6 characters in a line of an input file. Using the below code I am trying to do this but I don't know the syntax to do so, and I get a syntax error. Thanks.

for line in f:
    x = line[......$]

Here is the specific error:

File "bettercollapse.py", line 15
    x = line[......$]
               ^
SyntaxError: invalid syntax
The Nightman
  • 5,417
  • 8
  • 35
  • 66
  • possible duplicate of [Explain Python's slice notation](http://stackoverflow.com/questions/509211/explain-pythons-slice-notation) – user Jun 11 '15 at 18:06

2 Answers2

1

You can do that by slicing as

for line in f:
    x = line[-6:]
  • The negative indexing accesses the nth (here 6th) element from the end of the string.

  • The column is followed by nothing, which means that it continues till the end of the string.

    That is here it takes elements from -6 to end of string, the last 6 elements.

Example

>>> string = "asdfasdfqwerqwerqwer"
>>> string[-6:]
'erqwer'

Note

It do count the \n that may be in the file. So for safety the for loop can be written as

>>> with open('test', 'r') as input_file:
...     for line in input_file:
...             print line[-7:-1]
... 
erqwer
>>> 

where as the older version would be

>>> with open('test', 'r') as input_file:
...     for line in input_file:
...             print line[-6:]
... 
rqwer
Community
  • 1
  • 1
nu11p01n73R
  • 25,677
  • 2
  • 36
  • 50
0

Regexps aren't the right tool for this; slicing is.

for line in f:
    print(line[-6:])  # print last 6 characters of line
Community
  • 1
  • 1
AKX
  • 123,782
  • 12
  • 99
  • 138