有人能帮我使我的程序案例不敏感吗?

2024-10-01 00:32:56 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我的代码到目前为止,现在它是区分大小写的。我尝试将字符串变为小写(使用.lower),但没有成功。有人能帮忙吗?你知道吗

file=open("numbertext.txt","w")
my_string= input("Enter a sentence.   ")
splitted = my_string.split()

d = {}
l=[]
for i,j in enumerate(splitted):
    if j in d:
        l.append(d[j])
    else:
        d[j]=i
        l.append(i)
print(l)

file.write(str(l))

[0, 1, 2, 3, 4, 5, 6, 7, 8, 9, 4, 11, 5, 6]

file=open("newfile.txt","w")

file.close

Tags: 字符串代码intxtinputstringmyopen
3条回答

函数lower返回转换后的字符串,不转换字符串本身。您应该在这里使用lower

splitted = my_string.lower().split()

代码优化:

d = {}
l=[]
for i,j in enumerate(splitted):
    l.append(d.setdefault(j, i))


with open("numbertext.txt","w") as f:
    f.write(str(l))

splitted = my_string.lower().split()就可以了

在Python中something.method不调用该方法-它只访问该名称的属性。所以在您的例子中,您需要执行file.close()(或者更好地使用with语句),对于您的原始问题:使用somestring.lower()。你知道吗

相关问题 更多 >