将字符串拆分为字母组,忽略空格

时间:2021-01-24 10:48:59

标签: python string split

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

示例 1:

hello world

输出:

hell owor ld

示例 2:

if you can dream it, you can do it

输出:

ifyo ucan drea mit, youc ando it

5 个答案:

答案 0 :(得分:3)

一种选择是从输入中去除所有空格,然后在模式 re.findall 上使用 .{1,4} 来查找所有 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

答案 1 :(得分:1)

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,你好吗?

答案 2 :(得分:1)

这里有一个不需要导入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

答案 3 :(得分:0)

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

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

答案 4 :(得分:-1)

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