Python取代','在引号内,但保留其他逗号,然后删除字符串中的引号

时间:2017-10-04 22:47:25

标签: python-3.x

我目前有一个字符串输出,如下所示:

Shares Mil,"1,457","1,388","1,341","1,287","1,214","1,155","1,103","1,010",983,959,949

我需要它看起来像这样:

Shares Mil,1457,1388,1341,1287,1214,1155,1103,1010,983,959,949

基本上我想删除引号括起来的数字中的逗号,然后能够使用.split(',')将逗号分隔成字符串。

我有一个想法是使用正则表达式在引号中找到逗号以删除逗号,然后使用.replace('"','')删除引号,但我不确定如何使用。

我可以通过逗号.split()删除引号,然后手动加入分隔的数字,但必须有一种更有效的方法,所以我想我会寻求帮助。< / p>

谢谢!

1 个答案:

答案 0 :(得分:1)

使用通常的python字符串函数,没有一种简单的方法来区分你想要保留的逗号和你想要丢弃的逗号。

您需要使用regular expressions,即regex来删除*仅引用号码内的,

这是调试正则表达式的online regex compileranother

这是python的re.sub()函数,用于在正则表达式matches上执行搜索和替换操作。

为此,您还需要在文件顶部import re。您不需要下载或安装任何内容来执行此操作,因为它是Python的一部分。

import re

input_str = 'Shares Mil,"1,457","1,388","1,341","1,287","1,214","1,155","1,103","1,010",983,959,949'
desired_output_str = 'Shares Mil,1457,1388,1341,1287,1214,1155,1103,1010,983,959,949'

# use regex to *only* remove commas that are part of a number within a string
# matches commas that are followed immediately by a one or more digits and then double-quote
regex_pattern = r',(?=\d+")'

# we want to replace *those* commas with empty string (aka delete them)
replacement = ''

comma_less_numbers_str = re.sub(regex_pattern, replacement, input_str)
print(comma_less_numbers_str, "\n")

# now it's easy: just remove the "
output_str = comma_less_numbers_str.replace('"', '')

print(output_str)
print(output_str == desired_output_str)
print(desired_output_str)

repl.it for this solution

正则表达式非常强大,并且比您想象的更频繁。它简化了您将遇到的许多任务 我强烈建议你花一天的时间来熟悉一下它的命名 一旦你开始看它,它实际上很容易。 我上面链接了文档。
您还可以将应用程序下载到手机中,以便在业余时间以一口大小的速度快速学习正则表达式。