[英]Add spaces in-between each letter in string, then not have space at the end
[英]How to output a string with a space between each letter
例如,如果我输入“ I love dogs
,则需要看起来像这样:
I l o v e d o g s
这段代码无法满足我的需要:
def spaceitout(source):
pile = ""
for letter in source:
pile = pile+letter
print pile
print pile
def evenly_spaced(string_,space_= 1):
import re
return (' '*space_).join([c for c in re.split(r'(\w)',string_) if c.isalpha()])
print(evenly_spaced(" This a long story ",2))
T h i s a l o n g s t o r y
这会满足您的需求吗?
pile = ' '.join(source)
这将使用“源”的元素,并以单个空间将它们连接起来作为连接器。
如果只需要将字母分开,则仅构建字母列表,然后将其加入:
pile = ' '.join([c for c in source if c.isalpha()])
字母之间的空格:
def spaceitout(source, count):
return (' '*count).join([letter for letter in source.replace(' ','')])
单词之间的空格:
def spaceitout(source, count):
return (' '*count).join(source.split())
所有字符之间的空格:
def spaceitout(source, count):
return (''.join([c + (' '*count) for c in source]).strip())
简单的答案是:
def spaceitout(source):
pile = ""
for letter in source:
pile = pile + letter + " "
pile = pile[:-1] #Strip last extraneous space.
print pile
允许您指定单词之间的空格和字符之间的空格。 根据BigOldTree提供的答案
def space_it(text, word_space=1, char_space=0):
return (' '*word_space).join([(' '*char_space).join(x) for x in text.split(' ')])
注意:这会将输入文本中的两个空格视为在它们之间有一个“不可见的单词”,如果text.split(' ')
, text.split(' ')
更改为text.split()
。
我认为这就是您想要的:
line = 'I love dogs'
for i in line:
if i != ' ':
print i,
else:
print '',
使用itertools:
import itertools
def space_word(word, spaces_count=1):
if spaces_count < 1:
raise ValueError("spaces_count < 1")
def space_word_wrapped(word, spaces_count):
letters = itertools.chain.from_iterable(zip(word, itertools.cycle(" ")))
skipped = 0 # have to keep track of how many letter skips
# or else from_word starts breaking!
# TODO : better implementation of this
for i, lett in enumerate(letters, start=1):
from_word = (i + skipped) % 2
if lett.isspace() and from_word:
if spaces_count == 1:
next(letters)
skipped += 1
continue # and skip the space itself
elif spaces_count == 2:
continue # just count the space
elif spaces_count == 3:
pass # count everything
else: # spaces_count >= 4
yield from [" "] * (spaces_count - 3)
yield lett
return ''.join(space_word_wrapped(word, spaces_count)).rstrip()
仅在此处使用迭代器可能会更便宜,但我喜欢嵌套函数方法中的生成器。 告我 :)
这会列出您的单词('his'= ['h','i','s'],然后用空格而不是逗号将其连接起来。
def space(word):
return ' '.join(list(word))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.