python连接字符串中的单个字符

时间:2019-05-17 10:53:40

标签: python join split

输入:

str1 = "a b abcd a b"

所需的输出:

"ab abcd ab"

如何仅删除字符串中单个字符之间的空格?

我想我不能使用split and join,因为它会标记所有内容,然后不在乎子字符串的长度。

2 个答案:

答案 0 :(得分:3)

这里是使用re.sub的选项。我们可以按照以下模式进行匹配:

(?<=\b[a-z]) (?=[a-z]\b)

,然后用空字符串替换,以删除目标空间。

input = "a b abcd a b"
output = re.sub(r'(?<=\b[a-z]) (?=[a-z]\b)', '', input)
print(output)

ab abcd ab

使用的正则表达式模式表明:

(?<=\b[a-z])   assert that what precedes is a single letter, which itself
               is preceded by a word boundary
[ ]            match a single space (brackets used for clarity only)
(?=[a-z]\b)    assert that what follows is also a single letter, which again
               is followed by a word boundary

答案 1 :(得分:1)

您也可以反过来考虑:垫上长弦

def padLong(item):
    if len(item) == 1:
        return item
    return ' ' + item + ' '

str1 = "a b abcd a b abc abcd"

strs = str1.split()
print(strs)

strs = ''.join([padLong(item) for item in strs])
print(strs)

strs = strs.split()
strs = ' '.join(strs)
print(strs)

输出:

['a', 'b', 'abcd', 'a', 'b', 'abc', 'abcd']
ab abcd ab abc  abcd 
ab abcd ab abc abcd