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,609
  • 13
  • 41
  • 74
  • 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
  • 26,397
  • 3
  • 39
  • 52
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
  • 152,115
  • 15
  • 115
  • 172