我的txt文件包含单词列表,如下所示:
Polynomial
我想删除每个单词中的最后一个字母,如果该字母是" a"或" o"。
我对此非常陌生,所以请简单解释一下。
答案 0 :(得分:1)
re.sub(r"[ao]$","",word)
这应该为你做。
答案 1 :(得分:1)
试试这个:
Enter the first character: 12
Enter the second character: The characters are 1 and 2
答案 2 :(得分:0)
首先读取文件并分割线条。如果满足条件,则切断最后一个字符,并将新字符串附加到包含已分析和修改的字符串/行的列表中:
#!/usr/bin/env python3
# coding: utf-8
# open file, read lines and store them in a list
with open('words.txt') as f:
lines = f.read().splitlines()
# analyse lines read from file
new_lines = []
for s in lines:
# analyse last char of string,
# get rid of it if condition is fulfilled and append string to new list
s = s[:-1] if s[-1] in ['a', 'o'] else s
new_lines.append(s)
print(new_lines)