简体   繁体   English

从不需要的字符中删除数组

[英]strip array from unwanted characters

I have an array as below: 我有如下数组:

>>>tags = ['frankie', "franki's car", 'car']

here I just want to replace double quotes to single quote, and remove the apostrophe from the array indexes. 在这里,我只想将双引号替换为单引号,并从数组索引中删除apostrophe

So I expect to have something like below: 所以我希望有类似下面的内容:

>>> tags
['frankie', 'frankis car', 'car']

any help? 有什么帮助吗? thanks. 谢谢。

You can use a list comprehension to remove the single quotes: 您可以使用列表推导删除单引号:

[t.replace("'", '') for t in tags]

The double quotes are an artefact of how Python represents string literals; 双引号是Python如何表示字符串文字的伪像; it'll use single quotes unless there is a single quote in the string , at which point it'll use double quotes to avoid having to use a backslash to escape that character. 除非字符串中有单引号,否则它将使用单引号,此时它将使用双引号,以避免必须使用反斜杠来转义该字符。 If you have a string with both types Python uses single quotes again and escapes any double quotes in the value: 如果您拥有两种类型的字符串,Python会再次使用单引号并将值中的任何双引号转义:

>>> "No single quotes"
'No single quotes'
>>> "A single quote: '"
"A single quote: '"
>>> "Both types: \" and '"
'Both types: " and \''

Demo: 演示:

>>> tags = ['frankie', "franki's car", 'car']
>>> [t.replace("'", '') for t in tags]
['frankie', 'frankis car', 'car']

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

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