【问题标题】:Removing different types of double quotes from string?从字符串中删除不同类型的双引号?
【发布时间】:2019-09-21 18:49:23
【问题描述】:

我有一个名称列表,其中包含以英寸为单位的大小。如:

华硕 VP248QG 24''

明基 XYZ123456 32"

如您所见,名字的英寸有双单引号,而第二个名字有正常的双引号。

我有这个代码来删除这些尺寸,因为我不需要它们:

def monitor_fix(s):
    if ('"' in s):
        return re.sub(r'\s+\d+(?:\.\d+)"\s*$', '', str(s))
    if ("''" in s):
        return re.sub(r"\s+\d+(?:\.\d+)''\s*$", '', str(s))

但它只删除普通的双引号,而不是双单引号。如何处理?

【问题讨论】:

  • re.sub(r'\'|\"','',your_text) 怎么样?
  • 您是否只想删除所有出现的"''?正则表达式似乎有点矫枉过正。
  • 将结果分配回s并在最后一个if之后使用return
  • @DanielRoseman 我想删除所有出现在一个空格和引号之间的任何数字和引号。所以我正在尝试完全删除尺寸和英寸符号。
  • 您可以简单地使用一个正则表达式,['"]+(有单引号和双引号)也可以使用您的主正则表达式来检查数字

标签: python string subset quotes


【解决方案1】:

您可以简单地使用 string[:] 删除最后 4 - 5 个符号

list = ["Asus VP248QG 24''", 'BenQ XYZ123456 32"']

for i in range(len(list)):
    if "''" in list[i]:
        list[i] = list[i][:-5]
    if '"' in list[i]:
         list[i] = list[i][:-4]
    print(list[i])

【讨论】:

    【解决方案2】:

    假设大小总是用空格很好地分隔,我们可以简单地删除包含引号的“单词”。加分点,因为大小也可以在字符串中的任何位置。

    products = ["Asus VP248QG 24'' silver", 'BenQ XYZ123456 32"']
    
    for n, product in enumerate(products):
    
        product_without_size = ""
        for word in product.split(" "):
            if not("''" in word or '"' in word):   # If the current word is not a size,
                product_without_size += word + " " # add it to the product name (else skip it).
        products[n] = product_without_size.rstrip(" ")
    
    print(products) # ['Asus VP248QG silver', 'BenQ XYZ123456']
    

    使用原始帖子的格式,它看起来像这样:

    def monitor_fix(product):
    
        product_without_size = ""
        for word in product.split(" "):
            if not("''" in word or '"' in word):   # If the current word is not a size,
                product_without_size += word + " " # add it to the product name (else skip it).
        return product_without_size.rstrip(" ")
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-10-09
      • 2012-09-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多