Python按不同方式拆分字符串。完全停止

时间:2015-04-02 22:31:55

标签: python string split

嘿,我希望能够改变我的字符串被分割,比如第三个句号,或者第二个是我的代码

file = "hey there. this is some demo code. will you nice people please help me."

我想在之后将字符串拆分为第二个句号,这样看起来就像

"hey there. this is some demo code."

3 个答案:

答案 0 :(得分:0)

".".join(file.split(".")[2:])

file.split(".",2)[2:]

这些使用str.split()2 / 3),str.join()2 / 3)和切片({{3} } / 2)。没有理由为此使用循环或正则表达式。

答案 1 :(得分:0)

我会做这样的事情:

readf = open("split.txt")

for line in readf:

  a=line.split(".")

readf.close()

print (a[:2])

基本上,您将该行存储在a中并将其拆分为“。”然后使用您可以随意使用的子序列。 例如a [2:3]给你第二行和第三行,而[:3]给你全部三个。

答案 2 :(得分:-1)

一个粗略的方法是使用一个计数器并循环遍历字符串,添加每个字符直到达到停止限制。

firstString = ""
secondString = ""
stopsAllowed = 1
stopsFound = 0
for i in range(0,len(file)):
  if file[i] == ".":
    stopsFound += 1
  if stopsFound <= stopsAllowed:
    firstString += file[i]
  else:
    secondString += file[i]