从其余字符串中拆分前导空格

时间:2014-11-05 03:40:12

标签: python string split

我不确定如何准确传达我想要做的事情,但我正在尝试创建一个功能来分割我的一部分字符串(领先的空白),以便我可以使用脚本的不同部分对其进行编辑,然后在更改后再将其添加到我的字符串中。

所以我要说我有字符串:

"    That's four spaces"

我想分开它,所以我最终得到:

"    " and "That's four spaces"

4 个答案:

答案 0 :(得分:2)

您可以使用re.match

>>> import re
>>> re.match('(\s*)(.*)', "    That's four spaces").groups()
('    ', "That's four spaces")
>>>

(\s*)在字符串的开头捕获零个或多个空白字符,(.*)获取其他所有字符。

请记住,这些字符串在Python中是不可变的。从技术上讲,你不能编辑他们的内容;你只能创建新的字符串对象。


对于非正则表达式解决方案,您可以尝试这样的方法:

>>> mystr = "    That's four spaces"
>>> n = next(i for i, c in enumerate(mystr) if c != ' ') # Count spaces at start
>>> (' ' * n, mystr[n:])
('    ', "That's four spaces")
>>>

此处的主要工具是nextenumerategenerator expression。这个解决方案可能比Regex更快,但我个人认为第一个更优雅。

答案 1 :(得分:1)

为什么不尝试匹配而不是分裂?

>>> import re
>>> s = "    That's four spaces"
>>> re.findall(r'^\s+|.+', s)
['    ', "That's four spaces"]

<强>解释

  • ^\s+匹配一行开头的一个或多个空格。
  • |
  • .+匹配所有剩余的字符。

答案 2 :(得分:1)

一种解决方案是对字符串进行lstrip,然后计算出已删除的字符数。然后,您可以根据需要“修改”字符串,并通过将空格添加回字符串来完成。我认为这不会适用于制表符,但对于空格,它似乎只能完成工作:

my_string = "    That's four spaces"
no_left_whitespace = my_string.lstrip()
modified_string = no_left_whitespace + '!'
index = my_string.index(no_left_whitespace)
final_string = (' ' * index) + modified_string

print(final_string) #     That's four spaces!

这是一个简单的测试,以确保我们做得对,通过:

assert final_string == my_string + '!'

答案 3 :(得分:0)

你可以做的一件事是用string.that

列出一个列表
x="    That's four spaces"
y=list(x)
z="".join(y[0:4]) #if this is variable you can apply a loop over here to detect spaces from start
k="".join(y[4:])
s=[]
s.append(z)
s.append(k)
print s

这是一个非正则表达式解决方案,不需要任何导入

相关问题