Search code examples
importoutputcharacterstring-length

is there a reason why the len function displays the wrong lengh of a word (no spaces etc.)?


following scenario: I want to display the length of a random word selected from a simple .txt list like this:

composer
circulation
fashionable
prejudice
progress
salesperson
disappoint

I used the following code to display one of these words from the list:

random_word_generator = open("random_words.txt", "r")
random_words = list(random_word_generator)
secret_word = random.choice(random_words)

however, whenever I want to print the length of the word by using:

print("My secret word is " + str(len(secret_word)))

It shows the length of the word - 1 character

like:

progress --> should be 8 letters, but python displays 7...

Do you know how this issue could be solved?

Btw: there are no spaces whatsoever in my .txt file

Kind Regards and many thanks in advance


Solution

  • You should mention the language you're using in the title and the tags.

    To your question: Can you please paste the full code you're using? I tried your example, and it displays the correct length of each word (+ 1 for the newline character, which you could remove by calling .strip()), so I'm guessing you do something different.

    random_word_generator = open("random_words.txt", "r")
    random_words = list(random_word_generator) # ['composer\n', 'circulation\n', 'fashionable\n', 'prejudice\n', 'progress\n', 'salesperson\n', 'disappoint\n']
    secret_word = random.choice(random_words) # "progress\n"
    print("My secret word is " + str(len(secret_word))) # "My secret word is 9"
    print("My secret word w/o newline is " + str(len(secret_word.strip()))) # "My secret word w/o newline is 8"