gpt4 book ai didi

Python - 仅对某些字符串计算字符串的长度不准确

转载 作者:行者123 更新时间:2023-12-03 23:07:45 25 4
gpt4 key购买 nike

我是编程新手,正在尝试制作一个基本的刽子手游戏。出于某种原因,在从文本文件计算字符串长度时,某些单词的字符串长度计算不正确。有些字符串的值太高,有些太低。我似乎无法弄清楚为什么。我已经确保文本文件中没有空格,以便将空格计为一个字符。

import random

#chooses word from textfile for hangman
def choose_word():
words = []
with open("words.txt", "r") as file:
words = file.readlines()

#number of words in text file
num_words = sum(1 for line in open("words.txt"))
n = random.randint(1, num_words)

#chooses the selected word from the text file
chosen_word = (words[n-1])
print(chosen_word)

#calculates the length of the word
len_word = len(chosen_word)
print(len_word)

choose_word()
#obama returns 5
#snake, turtle, hoodie, all return 7
#intentions returns 11
#racecar returns 8
words.txt

snake
racecar
turtle
cowboy
intentions
hoodie
obama

最佳答案

使用 strip() .

string.strip(s[, chars])

Return a copy of the string with leading and trailing characters removed. If chars is omitted or None, whitespace characters are removed. If given and not None, chars must be a string; the characters in the string will be stripped from the both ends of the string this method is called on.



例子:
>>> ' Hello'.strip()
'Hello'

尝试这个:
import random

#chooses word from textfile for hangman
def choose_word():
words = []
with open("words.txt", "r") as file:
words = file.readlines()

#number of words in text file
num_words = sum(1 for line in open("words.txt"))
n = random.randint(1, num_words)

#chooses the selected word from the text file
chosen_word = (words[n-1].strip())
print(chosen_word)

#calculates the length of the word
len_word = len(chosen_word)
print(len_word)

choose_word()

关于Python - 仅对某些字符串计算字符串的长度不准确,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61249543/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com