【问题标题】:Convert the string to a string in which the words are separated by spaces and only the first word starts with an uppercase letter [duplicate]将字符串转换为单词以空格分隔且只有第一个单词以大写字母开头的字符串[重复]
【发布时间】:2021-01-31 23:42:13
【问题描述】:

我正在尝试制作一个脚本,该脚本将接受一个字符串作为输入,其中所有单词都一起运行,但每个单词的第一个字符都是大写的。它应该将字符串转换为单词以空格分隔的字符串,并且只有第一个单词以大写字母开头。

例如(输入):

"StopWhateverYouAreDoingInterestingIDontCare"

预期输出:

"Stop whatever you are doing interesting I dont care"

这是我目前写的:

string_input = "StopWhateverYouAreDoingInterestingIDontCare"

def organize_string():
   start_sentence = string_input[0] 
   index_of_i = string_input.index("I")
   for i in string_input[1:]: 
      if i == "I" and string_input[index_of_i + 1].isupper(): 
           start_sentence += ' ' + i 
      elif i.isupper():      
           start_sentence += ' ' + i.lower()
      else: 
           start_sentence += i
return start_sentence

虽然这会处理某些部分,但我正在努力区分字母“I”是单个还是整个单词。这是我的输出:

"Stop whatever you are doing interesting i dont care"

单个“I”需要大写,而“Interesting”中的“I”应该小写“interesting”。

我将非常感谢所有帮助!

【问题讨论】:

标签: python


【解决方案1】:

在本例中使用正则表达式。

import re
s = "StopWhateverYouAreDoingInterestingIDontCare"
t = re.sub(r'(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z])', ' ', s)

解释:

(?&lt;=[a-z])(?=[A-Z]) - 小写字母后跟前瞻大写字母

| -(表示or

(?&lt;=[A-Z])(?=[A-Z]) - 大写字母后跟前瞻大写字母

当有一个小写字母后跟一个大写字母时,此正则表达式替换一个空格,或者,当有一个大写字母后跟一个大写字母时。

更新:这不会正确地小写单词(I 和 first_word 除外)

UPDATE2:解决方法是:

import re

s = "StopWhateverYouAreDoingInterestingIDontCare"

first_word, *rest = re.split(r'(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z])', s)

rest = [word.lower() if word != 'I' else word for word in rest]

print(first_word, ' '.join(rest))

打印:

Stop whatever you are doing interesting I dont care

更新 3:我查看了为什么您的代码未能正确形成句子(我应该首先这样做,而不是发布我自己的解决方案 :-))。

这是更正后的代码,其中包含有关更改的一些说明。

string_input = "StopWhateverYouAreDoingInterestingIDontCare"

def organize_string():
   start_sentence = string_input[0] 
   #index_of_i = string_input.index("I")
   for i, char in enumerate(string_input[1:], start=1):
      if char == "I" and string_input[i + 1].isupper(): 
           start_sentence += ' ' + char          
      elif char.isupper():      
           start_sentence += ' ' + char.lower()
      else: 
           start_sentence += char
      
   return start_sentence

print(organize_string())

!。我注释掉了 index_of_i = string_input.index("I") 行,因为它没有满足您的需要(它找到了 first 大写 I 的索引,而不是应该独立的 I(它找到了 I在Interesting 而不是IDont 进一步在string_input 字符串中)。这不是一个正确的陈述。

  1. for i, char in enumerate(string_input[1:], 1) enumerate 表示字符串中字母的索引从 1 开始(因为 string_input[1:] 从索引 1 开始,所以它们是同步的)。 istring_input 中字母的索引。

我将i 更改为char 以更清楚地表明char 是角色。除了这些更改之外,代码与您编写的一样。

现在程序给出了正确的输出。

【讨论】:

  • 非常感谢您的解决方案和解释,我每天都在学习很多新东西!谢谢! (更新:它不会小写单词的第一个字母)
【解决方案2】:
string_input = "StopWhateverYouAreDoingInterestingIDontCare"
counter = 1
def organize_string():
    global counter
    start_sentence = string_input[0] 
    for i in string_input[1:]: 
        if i == "I" and string_input[counter+1].isupper():
            start_sentence += ' ' + i
        elif i.isupper():      
            start_sentence += ' ' + i.lower()
        else: 
            start_sentence += i
        counter += 1
    print(start_sentence)

organize_string()

我对您的程序进行了一些更改。我使用计数器来检查索引位置。我得到了你的预期输出:

Stop whatever you are doing interesting I dont care 

【讨论】:

  • 哦,我从没想过采用这种方法。非常感谢您的帮助,谢谢!
【解决方案3】:
s = 'StopWhateverYouAreDoingInterestingIDontCare'
 
ss = ' '

res = ''.join(ss + x if x.isupper() else x for x in s).strip(ss).split(ss)

sr = ''

for w in res:

  sr = sr + w.lower() + ' '
  
print(sr[0].upper() + sr[1:])

输出

Stop whatever you are doing interesting i dont care 

【讨论】:

    【解决方案4】:
    I hope this will work fine :-
    string_input = "StopWhateverYouAreDoingInterestingIDontCare"
    def organize_string():
        i=0
        while i<len(string_input):
            if string_input[i]==string_input[i].upper() and i==0 :
                print(' ',end='')
                print(string_input[i].upper(),end='')
            elif string_input[i]==string_input[i].upper() and string_input[i+1]==string_input[i+1].upper():
                print(' ',end='')
                print(string_input[i].upper(),end='')
            elif string_input[i]==string_input[i].upper() and i!=0:
                print(' ',end='')
                print(string_input[i].lower(),end='')
            if string_input[i]!=string_input[i].upper():
                print(string_input[i],end='')
            i=i+1
    organize_string()
    

    【讨论】:

      【解决方案5】:

      这是一种利用re 包根据大写字符拆分字符串的解决方案。 [Docs]

      import re
      text = "StopWhateverYouAreDoingInterestingIDontCare"
      
      # Split text by upper character
      text_splitted = re.split('([A-Z])', text)
      print(text_splitted)
      

      正如我们在分隔符(大写字符)下方的输出中看到的,并且保留了前后的文本。这意味着大写字符后面总是跟单词的其余部分。空的第一个字符串源自第一个大写字符,即第一个分隔符。

      # Output of print
      [
          '',
          'S', 'top',
          'W', 'hatever',
          'Y', 'ou', 
          'A', 're', 
          'D', 'oing', 
          'I', 'nteresting', 
          'I', '', 
          'D', 'ont', 
          'C', 'are'
      ]
      

      正如我们所见,第一个字符总是跟在单词的其余部分之后。通过将两者结合起来,我们得到了拆分词。这也使我们能够通过I 轻松处理您的特殊情况

      # Remove first character because it is always empty if first char is always upper
      text_splitted = text_splitted[1:]
      
      result = []
      for i in range(0, len(text_splitted), 2):
          word = text_splitted[i]+text_splitted[i+1]
      
          if (i > 0) and (word != 'I') :
              word = word.lower()
      
          result.append(word)
      
      result = ' '.join(result)
      

      【讨论】:

        【解决方案6】:

        split将句子转换成单个单词。如果您在此列表中找到 "I" 一词,请不要理会它。留下第一个单词。所有其他单词,您都转换为小写。

        【讨论】:

        • 你的意思是在句子返回输出后拆分?
        • 是的,在您插入空格之后。更好的是,进行拆分而不是插入空格。你能从那里做编码吗?
        【解决方案7】:

        你必须像这样使用一些字符串操作:

        output=string_input[0]
        for l in string_input[1:]:
             if l.islower():
                     new_s+=l
             else:
                     new_s+=' '+l.lower()
        print(output)
        

        【讨论】:

          猜你喜欢
          • 2021-03-12
          • 2010-12-01
          • 1970-01-01
          • 2013-09-06
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2022-01-22
          相关资源
          最近更新 更多