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
1

2 Answers 2

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
Sign up to request clarification or add additional context in comments.

Comments

0

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

for line in f:
    print(line[-6:])  # print last 6 characters of line

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.