【问题标题】:Split a string into groups of letters, ignoring whitespace [duplicate]将字符串拆分为字母组,忽略空格[重复]
【发布时间】:2021-04-28 08:46:22
【问题描述】:

我正在尝试将一个字符串分成 4 个字母的组。 不在字符串中的列表中。 不使用导入

示例 1:

hello world

输出:

hell owor ld

示例 2:

if you can dream it, you can do it

输出:

ifyo ucan drea mit, youc ando it

【问题讨论】:

标签: python string split


【解决方案1】:

请在下面找到我的解决方案并附上解释

string  = "if you can dream it, you can do it"

string = string.replace(' ','') #replace whitespace so all words in string join each other

n = 4 # give space after every n chars
  

out = [(string[i:i+n]) for i in range(0, len(string), n)] # Using list comprehension to adjust each words with 4 characters in a list
  
# Printing output and converting list back to string 
print(' '.join(out)) 

输出:

ifyo ucan drea mit, youc ando it

【讨论】:

    【解决方案2】:
    pattern = "if you can dream it, you can do it"
    
    i = 0
    result = ""
    for s in pattern:
        if not s == " ":
            if i == 4:
                i = 0
                result += " "
            result += s
            i += 1
    print(result)
    

    输出:

    ifyo ucan drea mit, youc ando it
    

    【讨论】:

      【解决方案3】:

      这里是一个不需要导入re的解决方案:

      input_string = "if you can dream it, you can do it"
      
      # The number of characters wanted
      chunksize=4
      
      # Without importing re
      
      # Remove spaces
      input_string_without_spaces = "".join(input_string.split())
      
      # Result as a list
      result_as_list = [input_string_without_spaces[i:i+chunksize] for i in range(0, len(input_string_without_spaces), chunksize)]
      
      # Result as string
      result_as_string = " ".join(result_as_list)
      
      print(result_as_string)
      

      输出:

      ifyo ucan drea mit, youc ando it
      

      【讨论】:

        【解决方案4】:
        full_word = "hello world, how are you?"
        full_word = full_word.replace(" ", "")
        output = ""
        for i in range(0, len(a)-8, 4):
            output += full_word[i:i + 4]
            output += " "
        print(output)
        

        输出 = 地狱 owor ld,你好吗?

        【讨论】:

          【解决方案5】:

          一种选择是从输入中删除所有空格,然后在模式 .{1,4} 上使用 re.findall 来查找所有 4 个(或许多可用的)字符块。然后将该列表按空格连接在一起以生成最终输出。

          inp = "if you can dream it, you can do it"
          parts = re.findall(r'.{1,4}', re.sub(r'\s+', '', inp))
          output = ' '.join(parts)
          print(output)
          

          打印出来:

          ifyo ucan drea mit, youc ando it
          

          【讨论】:

          • 任何不使用 import 的想法?
          • @rolaMulla 使用import re
          猜你喜欢
          • 2015-09-14
          • 2016-01-16
          • 2015-06-11
          • 2013-04-18
          • 1970-01-01
          • 1970-01-01
          • 2013-08-19
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多