如何替换字符串中某个特定字符的所有出现? [英] How do you replace all the occurrences of a certain character in a string?

查看:106
本文介绍了如何替换字符串中某个特定字符的所有出现?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在将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 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.

有更好的方法吗?

推荐答案

问题是您对replace的结果没有执行任何操作.在Python中,字符串是不可变的,因此任何处理字符串的操作都将返回新字符串,而不是修改原始字符串.

The problem is you're 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.

line[8] = line[8].replace(letter, "")

这篇关于如何替换字符串中某个特定字符的所有出现?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆