嘿,我希望能夠改變我的字符串在被拆說第三句號或這裏的第二個是我的代碼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