+ 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 RĂ©ponses
+ 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