Why len() function counts \n in a word? | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 1

Why len() function counts \n in a word?

Hello, in one of the tasks I need to index some books with the first letter and number of symbols in name of the books. Example: “Harry Potter\n” -> H12. So I don’t understand why len() function counts \n as symbol? My code: file = open("/usercode/files/books.txt", "r") lines = file.readlines() n = 0 try: for line in lines: first_line = str(lines[n]) first_word = first_line[0] index = str(len(first_line)) print(first_word[0]+index) n += 1 finally: file.close()

4th Jul 2023, 1:55 PM
Eldar Kulzhanov
Eldar Kulzhanov - avatar
4 Answers
+ 3
Because '\n' also a character.
4th Jul 2023, 1:57 PM
Jayakrishna 🇮🇳
+ 1
But it is just an intendation, isn’t it?
4th Jul 2023, 1:59 PM
Eldar Kulzhanov
Eldar Kulzhanov - avatar
+ 1
No. It is part of word. You can see in 'Harry Potter\n'. Just remove '\n' from first_line before. Use replace function...
4th Jul 2023, 2:03 PM
Jayakrishna 🇮🇳
+ 1
Thank you a lot
4th Jul 2023, 2:08 PM
Eldar Kulzhanov
Eldar Kulzhanov - avatar