with open("p022_names.txt","r") as f:
for line in f:
name=[str(v) for v in line.split(",")]
name.sort()
print(name)
tot=0
for i in range(len(name)):
tot=tot+sum(ord(letter)-64 for letter in name[i])
print(tot)
从文件中读取数据时,还会在名称中添加“和”。 如果名称为COLIN,则会在列表名称中另存为““ COLIN”'。 我如何解决它? 输入文件。
"MARY","PATRICIA","LINDA","BARBARA","ELIZABETH","JENNIFER","MARIA","SUSAN","MARGARET","DOROTHY","LISA","NANCY","KAREN","BETTY","HELEN","SANDRA","DONNA","CAROL","RUTH","SHARON","MICHELLE","LAURA","SARAH","KIMBERLY","DEBORAH","JESSICA","SHIRLEY","CYNTHIA","ANGELA","MELISSA","BRENDA","AMY","ANNA","REBECCA","VIRGINIA","KATHLEEN","PAMELA","MARTHA","DEBRA","AMANDA","STEPHANIE","CAROLYN","CHRISTINE","MARIE","JANET","CATHERINE","FRANCES","ANN","JOYCE","DIANE","ALICE","JULIE","HEATHER","TERESA","DORIS","GLORIA","EVELYN","JEAN","CHERYL","MILDRED","KATHERINE","JOAN","ASHLEY","JUDITH","ROSE","JANICE","KELLY","NICOLE","JUDY","CHRISTINA","KATHY","THERESA","BEVERLY","DENISE","TAMMY","IRENE","JANE","LORI","RACHEL","MARILYN","ANDREA","KATHRYN","LOUISE","SARA","ANNE","JACQUELINE","WANDA","BONNIE","JULIA","RUBY","LOIS","TINA","PHYLLIS","NORMA","PAULA","DIANA","ANNIE","LILLIAN","EMILY","ROBIN","PEGGY","CRYSTAL","GLADYS","RITA","DAWN","CONNIE","FLORENCE","TRACY","EDNA","TIFFANY","CARMEN","ROSA","CINDY","GRACE","WENDY","VICTORIA",
输出 ['“ MARY”','“ ...”','“ ...”',..]
答案 0 :(得分:1)
如果要从字符串中删除这些字符,则可以执行以下操作:
s = s.replace("\"","")
这将用空字符串替换"
的所有实例。
如果只希望在字符串的末尾删除它们,则可以这样做
s = s.strip("\"")
如果要确保只在两端删除一个引号,则可以执行以下操作:
if s.startswith("\""):
s = s[1:]
elif s.endswith("\""):
s = s[:-1]
如果您知道字符串始终带有引号,则可以将其简化为:
s = s[1:-1]
但是,该文件似乎是一个csv文件,最好使用csv
库来解析这些文件。
答案 1 :(得分:1)
您可以通过以下方法从Python字符串中删除开头和结尾的字符:
name = "'COLIN'"
print(name[1:-1])
这将打印
COLIN
代替
'COLIN'
答案 2 :(得分:1)
这是我的解决方案。它支持以逗号分隔的多行名称,也支持文件中的多行。
names = []
with open('p022_names.txt') as f:
for line in f:
names.extend(v.lower().strip('"').strip("'") for v in line.split(","))
names.sort()
for name in names:
tot = sum(ord(letter)-96 for letter in name)
print("{0}: {1}".format(name, tot))
答案 3 :(得分:-1)
with open("p022_names.txt","r") as f:
for line in f:
name=[str(v) for v in line.split(",")]
name.sort()
print(name)
我假设您看到这样的内容:
['"MARY"','"PATRICIA"'...]
如果我正确理解了您的问题,则希望同时删除'
和"
这两个字符。这里的'
字符表示列表的元素是字符串。 您的实际数据中没有这些。您只需要删除双引号。您无需担心单引号。您仅有的引号是从文件中读取的"
。
此外,您可以简化
name=[str(v) for v in line.split(",")]
到
name = line.split(",")