+ 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()
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:
...
+ 3
Probably because of the newline character.
Like when we output "\n" to the console, normally it is not displayed in text editors.
+ 2
😍😍do a strip()😍😍
y = len(i.strip())
+ 2
Faizan Ali Python? Or it is my English?😅
+ 1
Lochard thanks
0
What language is this
0
🥰🥰