+ 2

Why my code always add 1 to a number?

Inside the files is written: Harry Potter John wick Some Book The code is supposed to take the first letter of the above book names and print it with the lenght of the book titles. But the length is always one number higher. Like "Harry Potter" is supposed to be "H12" but it shows "H13". Can someone please explain this to me? try : file = open("/home/anwender/Desktop/Opening Files/Nesar.txt", "r") x = file.readlines() for i in x : y = len(i) a = i[0] print(a, y, sep="") finally : file.close()

19th Mar 2023, 5:43 AM
Engineer X
Engineer X - avatar
8 Réponses
+ 9
Engineer X , just 2 comment from my side: (1) as already mentioned, we need to remove all *newline sequences* that are included when reading from a file. all lines, *except the last one*, do have a trailing newline sequence *\n*. to accomplish this, we can use the string strip() methods: > strip() removes leading and trailing *whitespaces* which includes also the newline sequences. > rstrip() removes only trailing *whitespaces* > lstrip() removes only leading *whitespaces* > all of this methods do *not* touch *whitespaces* that are inside the strings. (2) instead of using a try... except... block, we can also use *with...* what is called a context manager. this does not need to have an explicitely *file.close()* with open('this_file.txt', 'r') as my_file: for item in my_file: ...
19th Mar 2023, 7:39 AM
Lothar
Lothar - avatar
+ 3
Probably because of the newline character. Like when we output "\n" to the console, normally it is not displayed in text editors.
19th Mar 2023, 5:48 AM
Lochard
Lochard - avatar
+ 2
😍😍do a strip()😍😍 y = len(i.strip())
19th Mar 2023, 6:26 AM
Bob_Li
Bob_Li - avatar
+ 2
Faizan Ali Python? Or it is my English?😅
19th Mar 2023, 6:52 AM
Lochard
Lochard - avatar
+ 1
Lothar yes, using context manager is the recommended way of reading files in Python.😎
19th Mar 2023, 7:48 AM
Bob_Li
Bob_Li - avatar
+ 1
Lochard thanks
20th Mar 2023, 3:24 AM
Faizan Ali
Faizan Ali - avatar
0
What language is this
19th Mar 2023, 6:45 AM
Faizan Ali
Faizan Ali - avatar
0
🥰🥰
21st Mar 2023, 2:50 AM
Angelique Muregwa