如何替换字符串中出现的所有特定字符?
我正在将 csv 读入 a
:
import csv
import collections
import pdb
import math
import urllib
def do_work():
a=get_file('c:/pythonwork/cds/cds.csv')
a=remove_chars(a)
print a[0:10]
def get_file(start_file): #opens original file, reads it to array
with open(start_file,'rb') as f:
data=list(csv.reader(f))
return (data)
def remove_chars(a):
badchars=['a','b','c','d']
for row in a:
for letter in badchars:
row[8].replace(letter,'')
return a
我想替换第 8 个中出现的所有 ['a','b','c','d']
具有空字符串的行的元素。 remove_chars
函数不起作用。
有更好的方法吗?
I am reading a csv into a
:
import csv
import collections
import pdb
import math
import urllib
def do_work():
a=get_file('c:/pythonwork/cds/cds.csv')
a=remove_chars(a)
print a[0:10]
def get_file(start_file): #opens original file, reads it to array
with open(start_file,'rb') as f:
data=list(csv.reader(f))
return (data)
def remove_chars(a):
badchars=['a','b','c','d']
for row in a:
for letter in badchars:
row[8].replace(letter,'')
return a
I would like to replace all occurrences of ['a','b','c','d']
in the 8th element of the line with empty string. the remove_chars
function is not working.
Is there a better way to do this?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
问题是您没有对
的结果执行任何操作替换
。在Python中,字符串是不可变的,因此任何操作字符串的操作都会返回一个新字符串,而不是修改原始字符串。The problem is that you are not doing anything with the result of
replace
. In Python strings are immutable so anything that manipulates a string returns a new string instead of modifying the original string.我会使用没有翻译表的翻译方法。它删除最新 Python 版本中第二个参数中的字母。
I would use the translate method without translation table. It deletes the letters in second argument in recent Python versions.
您确实应该有多个输入,例如一个用于名字、中间名、姓氏,另一个用于年龄。如果你想玩得开心,你可以尝试:
如果输入中有多个数字,这当然会失败。快速检查是:
并且:
You really should have multiple input, e.g. one for firstname, middle names, lastname and another one for age. If you want to have some fun though you could try:
This would of course fail if there is multiple numbers in the input. a quick check would be:
and also: