简体   繁体   English

如何在Python中从字符串中删除撇号

[英]How to remove apostrophe marks from a string in Python

I'd like to remove all the '' from each symbol using Python. 我想使用Python从每个符号中删除所有的''。

'MMM', 'AXP', 'AAPL', 'BA', 'CAT', 'CVX', 'CSCO', 'KO', 'DD', 'XOM', 'GE', 'GS', 'HD', 'IBM', 'INTC', 'JNJ', 'JPM', 'MCD', 'MRK', 'MSFT', 'NKE', 'PFE', 'PG', 'TRV', 'UNH', 'UTX', 'VZ', 'V', 'WMT', 'DIS' 'MMM','AXP','AAPL','BA','CAT','CVX','CSCO','KO','DD','XOM','GE','GS','HD ”,“ IBM”,“ INTC”,“ JNJ”,“ JPM”,“ MCD”,“ MRK”,“ MSFT”,“ NKE”,“ PFE”,“ PG”,“ TRV”,“ UNH”, 'UTX','VZ','V','WMT','DIS'

so I end up with: MMM, AXP, AAPL, BA, and so on... 所以我最终得到了:MMM,AXP,AAPL,BA等。

I tried 我试过了

str = 
'MMM’, ‘AXP’, ‘AAPL’, ‘BA’, ‘CAT’, ‘CVX’, ‘CSCO’, ‘KO’, ‘DD’, ‘XOM’, ‘GE’, ‘GS’, ‘HD’, ‘IBM’, ‘INTC’, ‘JNJ’, ‘JPM’, ‘MCD’, ‘MRK’, ‘MSFT’, ‘NKE’, ‘PFE’, ‘PG’, ‘TRV’, ‘UNH’, ‘UTX’, ‘VZ’, ‘V’, ‘WMT’, ‘DIS’

and then: 接着:

str2 = str.replace("''","")

but to no avail. 但无济于事。 any ideas? 有任何想法吗?

str.replace("‘", '').replace("’", '').replace("'", '')

(用双引号括起所有可能的引言)。

You are trying to replace '' which is not present in your string, just replace ' . 您正在尝试替换字符串中不存在的'' ,只需替换'

In [8]: a = "'a'"

In [9]: a
Out[9]: "'a'"

In [10]: a.replace("'", "") # This works
Out[10]: 'a'

In [11]: a.replace("''", "") # Your attempt
Out[11]: "'a'"

You're asking it to replace double-apostrophes with the code str.replace("''","") , but the apostrophes in your string are all individual. 您要求它用代码str.replace("''","")代替双撇号,但是字符串中的撇号都是单独的。 You should try just with a single like str.replace("'","") 您应该只尝试一个像str.replace("'","")

Also you might be running into a problem where they are not apostrophes, but single quotation marks, in which case you might need something like: 另外,您可能会遇到一个问题,它们不是单引号,而是单引号,在这种情况下,您可能需要以下内容:

str = str.replace("'", "")`
str = str.replace(u"\u2018", "")` # LEFT SINGLE QUOTATION MARK (U+2018)
str = str.replace(u"\u2019", "")` # RIGHT SINGLE QUOTATION MARK (U+2019)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM