+ 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()
4 Antworten
+ 3
Because '\n' also a character.
+ 1
But it is just an intendation, isn’t it?
+ 1
No. It is part of word. You can see in 'Harry Potter\n'.
Just remove '\n' from first_line before.
Use replace function...
+ 1
Thank you a lot