【问题标题】:Replacing multiple chars in a string with one character in Python [duplicate]在Python中用一个字符替换字符串中的多个字符[重复]
【发布时间】:2021-12-24 22:31:41
【问题描述】:

我正在寻找一种巧妙的方法来用一个字符串替换多个出现的特定字符。

例如:
我想转换这样的字符串:

string = '1;AA;;1234567;;some text;;some text;;;some text;some text;;;;;;1, 2, 3, 4, 5, 6;;;;;;;;;;;another text;;;;;;;;;;;;;'

到这里:

string = '1;AA;1234567;some text;some text;some text;some text;1, 2, 3, 4, 5, 6;another text;'

其中一种方法是使用基于列表的替换,但它需要制作一个非常庞大的列表,因为后续数据行中重复的数量会有所不同。

所以是这样的:

list = {';;':'';'.';;;'',';':'',';;;;':';',';;;;;':';'} #etc....
input = input.replace(list) 

这不是一个好主意。

关于我应该如何进行的任何建议?

问候,
J.

【问题讨论】:

  • 试试string = re.sub(r";+", ";", string)
  • 谢谢,就是这样:)

标签: python list replace str-replace


【解决方案1】:

使用split()、列表理解和join()

string = '1;AA;;1234567;;some text;;some text;;;some text;some text;;;;;;1, 2, 3, 4, 5, 6;;;;;;;;;;;another text;;;;;;;;;;;;;'
x = string.split(';')    # returns a list with '' instead of the repeating ';'
x = [i for i in x if i]  # deletes the '' from the list
y = ';'.join(x)          # join back the list to a string separated by ';'
print(y)

或者

string = ';'.join([i for i in string.split(';') if i])

【讨论】:

  • 你不需要 [] 里面的 .join
  • 看看结果的结尾:“;”不见了。
  • 感谢您的反馈
  • 感谢您的反馈,但是 - 正如 Timus 所写 - “;”正在被移除而不是减少到一种外观。
【解决方案2】:

试试

import re
input_string = '1;AA;;1234567;;some text;;some text;;;some text;some text;;;;;;1, 2, 3, 4, 5, 6;;;;;;;;;;;another text;;;;;;;;;;;;;'
print(re.sub(r";+", ";", input_string))

【讨论】:

  • 谢谢,一切正常!
猜你喜欢
  • 2015-03-17
  • 1970-01-01
  • 2019-05-05
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-01-11
  • 1970-01-01
相关资源
最近更新 更多