我需要取一行文字(单词),在行中点后的第一个空格处将其一分为二;例如:
The quick brown fox jumps over the lazy dog.
^
上面这条线的中点在位置22,这条线在单词“jumps”后面的空格处分开。你知道吗
如果您能看一下下面的代码并告诉我它是否是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.
我不确定Python的方式,但有一些技巧你可以使用:
您可以将行拆分为两半,然后搜索:
您不必使用
for
:不需要在if语句中使用
()
,也可以用于真/假使用is
:*通过@user7610注释,您可以使用:
只是为了好玩,这里有一个soulotion在一行:
输出:
我能给你的最好的“pythonic”提示是:“pythonic”方法是好的,直到它不可读为止,有时简单更好。你知道吗
我想这更清楚了
Pythonic是在可用的情况下使用内置函数。
string.index
在这里工作。你知道吗如果没有合适的位置断开字符串,则会引发ValueError。如果不是你想要的,你可能不得不调整代码。你知道吗
相关问题 更多 >
编程相关推荐