簡體   English   中英

分割帶有附加空格的Python字符串(句子)

[英]Split a Python string (sentence) with appended white spaces

可能可以拆分Python字符串(句子),以便在輸出中的單詞之間保留空格,但可以在拆分的子字符串中通過在每個單詞之后附加空格來保留它?

例如:

given_string = 'This is my string!'
output = ['This ', 'is ', 'my ', 'string!']

我大多數時候都避免使用正則表達式,但是在這里它非常簡單:

import re

given_string = 'This is my string!'
res = re.findall(r'\w+\W?', given_string)

# res ['This ', 'is ', 'my ', 'string!']

也許這會有所幫助嗎?

>>> given_string = 'This is my string!'
>>> l = given_string.split(' ')
>>> l = [item + ' ' for item in l[:-1]] + l[-1:]
>>> l
['This ', 'is ', 'my ', 'string!']

只需拆分並添加空格即可:

a = " "
output =  [e+a for e in given_string.split(a) if e]
output[len(output)-1] = output[len(output)-1][:-1]

最后一行是在謝謝之后刪除空格!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM