我需要取一行文字(单词)并在行的中点后面的第一个空格中将它分成两半; 例如:
The quick brown fox jumps over the lazy dog.
^
Run Code Online (Sandbox Code Playgroud)
上面一行的中点位于第22位,并且该行在"跳跃"一词之后的空格处分开.
如果您能查看以下代码并告诉我它是否是Pythonic,我将不胜感激.如果没有,请建议正确的方法.谢谢.(PS:我来自C++背景.)
midLine = len(line) / 2 # Locate mid-point of line.
foundSpace = False
# Traverse the second half of the line and look for a space.
for ii in range(midLine):
if line[midLine + ii] == ' ': # Found a space.
foundSpace = True
break
if (foundSpace == True):
linePart1 = line[:midLine + ii] # Start of line to location of space - 1.
linePart2 = line[midLine + ii + 1:] # Location of space + 1 to end of line.
Run Code Online (Sandbox Code Playgroud)
Pythonic是在可用的地方使用内置函数.string.index
做这个工作.
def half(s):
idx = s.index(' ', len(s) / 2)
return s[:idx], s[idx+1:]
Run Code Online (Sandbox Code Playgroud)
如果没有合适的地方来破坏字符串,这将引发ValueError.如果这不是您想要的,您可能需要调整代码.