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

2024-09-28 23:25:08 发布

您现在位置:Python中文网/ 问答频道 /正文

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

例1:

hello world

输出:

hell owor ld

例2:

if you can dream it, you can do it

输出:

ifyo ucan drea mit, youc ando it

Tags: 字符串youhello列表worldif字母it
3条回答

一个选项是从输入中去除所有空白,然后在模式.{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

以下是一个无需导入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
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)

输出=地狱还是地狱

相关问题 更多 >