【问题标题】:Python: Convert entire string to lowercase except for substrings in quotesPython:将整个字符串转换为小写,引号中的子字符串除外
【发布时间】:2016-06-03 07:54:25
【问题描述】:

我从用户输入收到了一个 python 字符串。

假设用户输入是这样的:

 I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'

如果这个字符串存储在一个名为 input_string 的变量中,并且我对其应用 .lower(),它会将整个字符串转换为小写。

input_string = input_string.lower()

结果:

i am enrolled in a course, 'mphil' since 2014. i love this 'so much'

这是我希望小写字母做的事情: 将所有内容(引号中的内容除外)转换为小写。

i am enrolled in a course, 'MPhil' since 2014. i love this 'SO MuCH'

【问题讨论】:

  • 您是否要考虑转义引号和/或未闭合引号?这会影响复杂性。
  • 没有。仅适用于封闭式报价。如果有未闭合的引号,则不会被视为带引号的子字符串
  • 您将如何处理“Mike 的车库在 Bob 的房子旁边”之类的问题?尽管单引号之间有字符,但它根本没有嵌入引号。
  • 我试图用单引号分割字符串,然后再次加入,但由于中间步骤看起来很麻烦
  • “迈克的车库在鲍勃的房子旁边”将导致“迈克的车库在鲍勃的房子旁边”

标签: python string lowercase


【解决方案1】:

我们可以结合使用否定前瞻、后瞻、应用单词边界和使用替换函数

>>> s = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'"
>>> re.sub(r"\b(?<!')(\w+)(?!')\b", lambda match: match.group(1).lower(), s)
"i am enrolled in a course, 'MPhil' since 2014. i love this 'SO MuCH'"

【讨论】:

  • 'SO MuCH MPhil' 可能会失败?
  • @YOU 是的,很好的例子,取决于 OP 在这种情况下想要做什么。
  • 希望将 'SO MuCH MPhil' 保留为 ''SO MuCH MPhil',没有大小写变化,因为整个事情都在引号之间
【解决方案2】:

这是我的第一个堆栈溢出答案。它绝对不是最优雅的代码,但它适用于您的问题。您可以将这个答案分解如下:

  1. 将字符串拆分为列表
  2. 创建两个子列表
  3. 将所需的子列表转换为更低
  4. 连接子列表
  5. 使用列表中的连接方法打印

代码如下:

string = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'"  
l = string.split()    #split string to list
lower_l = l[0:11]       
unchanged_l = l[11:]  #create sub-lists with split at 11th element
lower_l = [item.lower() for item in lower_l]    #convert to lower
l = lower_l + unchanged_l    #concatenate
print ' '.join(l)     #print joined list delimited by space

【讨论】:

    【解决方案3】:

    对于示例字符串和在单引号之间包含任意数量的单词的字符串,您可以使用此正则表达式模式来解决此问题。

    import re
    pat = re.compile(r"(^|' )([\w .,]+)($| ')") 
    
    input_string_1 = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO MuCH'"
    input_string_2 = "I am Enrolled in a course, 'MPhil' since 2014. I LOVE this 'SO SO MuCH'"
    
    output_string_1 = pat.sub(lambda match: match.group().lower(), input_string_1)
    output_string_2 = pat.sub(lambda match: match.group().lower(), input_string_2)
    
    print(input_string_1)
    print(output_string_1)
    print(input_string_2)
    print(output_string_2)
    

    【讨论】:

      猜你喜欢
      • 2016-11-19
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-11-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多