嘿,我希望能够改变我的字符串在被拆说第三句号或这里的第二个是我的代码Python以不同的方式分割字符串。句号
file = "hey there. this is some demo code. will you nice people please help me."
我想第二句号左右把字符串分裂它看起来像
"hey there. this is some demo code."
嘿,我希望能够改变我的字符串在被拆说第三句号或这里的第二个是我的代码Python以不同的方式分割字符串。句号
file = "hey there. this is some demo code. will you nice people please help me."
我想第二句号左右把字符串分裂它看起来像
"hey there. this is some demo code."
一个粗略的方式做到这一点是使用通过串计数器和循环,增加每一个字符,直到达到停止极限。
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]
非常不必要和复杂。会投票,但这会让我付出代价。 – 2015-04-02 23:45:56
我不确定我看到它是多么复杂 – 2015-04-03 03:39:53
也许并不复杂,但是很可怕的代码 – 2015-04-03 03:40:30
".".join(file.split(".")[2:])
或
file.split(".",2)[2:]
这些使用str.split()
(2/3),str.join()
(2/3),和切片(2/3)。没有理由为此使用循环或正则表达式。
awsome即时通讯将它放入可打印的文件中,并且它将其列出,有没有办法刚刚拿出第二个完整停止之前的位,并把它作为一个不同的字符串 – 2015-04-02 22:51:56
刚刚尝试过,并且在第二个完整停止后它没有切断,当我打印时 – 2015-04-02 22:57:15
请注意,这只在“。”上分裂,并非全部满座。 – 2015-04-02 23:20:20
我会做这样的事情:
readf = open("split.txt")
for line in readf:
a=line.split(".")
readf.close()
print (a[:2])
基本上你存储在一个行,分裂它“”然后使用你可以使用的子序列。 例如a [2:3]给你三声和三声,而[:3]给你所有三声。
我刚刚关闭我的电脑会尝试在早上谢谢 – 2015-04-02 23:15:08
好的祝你好运明天然后:) – Stakken 2015-04-02 23:16:50
请注意,这只分裂在''.'',并不是所有的停止。 – 2015-04-02 23:19:54
https://docs.python.org/2/library/stdtypes.html#str.split – nullstellensatz 2015-04-02 22:36:16
我不理解文档 – 2015-04-02 22:38:20
''。'。join(file.split('。')[: - 2 ])' – letsc 2015-04-02 22:38:23