所以假設我有這個字串
string = 'abcd <# string that has whitespace> efgh'
我想洗掉里面的所有空白<#...>并且不影響外面的任何東西<#...>
但是外面的字符<#...>也可以改變,所以<#...>不會處于固定位置。
我該怎么做?
uj5u.com熱心網友回復:
這不是一個復雜的操作。你只是像作為一個人一樣去做。找到兩個分隔符,保留第一個之前的部分,從中間洗掉空間,保留其余部分。
string = 'abcd <# string that has whitespace> efgh'
i1 = string.find('<#')
i2 = string.find('>')
res = string[:i1] string[i1:i2].replace(' ','') string[i2:]
print(res)
輸出:
abcd <#stringthathaswhitespace> efgh
uj5u.com熱心網友回復:
這個怎么樣...
string = 'abcd <# string that has whitespace> efgh'
s = string.split()
s = ' '.join( (s[0], ''.join(s[1:-1]), s[-1]) )
uj5u.com熱心網友回復:
如果 <#...> 始終存在,則查找字串的一種方法是使用正則運算式 (regex) 來搜索包含要修改的字符的字串部分。然后,您需要去除空白。
了解正則運算式需要一些時間,但它們可以是強大的工具。 正則運算式
轉載請註明出處,本文鏈接:https://www.uj5u.com/qukuanlian/441336.html
