A. python中,如何將字元串中的多個不等量空格改為改為逗號分隔
1、創建python代碼,testsplit.py;
B. python如何去除字元串裡面的空格
使用字元串的replace方法,第一個參數是被替換的字元,第二個參數是替換為的字元
s = '***a b c**'
s = s.replace(' ', '')
s = s.replace('*', '')
C. python去掉字元串所有空格
字元串,rm為要刪除的字元序列
str.strip(rm) : 刪除s字元串中開頭、結尾處,位於 rm刪除序列的字元
str.lstrip(rm) : 刪除s字元串中開頭(左邊)處,位於 rm刪除序列的字元
str.rstrip(rm) : 刪除s字元串中結尾(右邊)處,位於 rm刪除序列的字元
str.replace(『s1』,』s2』) : 把字元串里的s1替換成s2。故可以用replace(』 『,」)來去掉字元串里的所有空格
str.split() : 通過指定分隔符對字元串進行切分,切分為列表的形式。
去除兩邊空格:
>>> str = ' hello world '
>>> str.strip()
'hello world'
1
2
3
1
2
3
去除開頭空格:
>>> str.lstrip()
'hello world '
1
2
1
2
去除結尾空格:
>>> str.rstrip()
' hello world'
1
2
1
2
去除全部空格:
>>> str.replace(' ','')
'helloworld'
1
2
1
2
將字元串以空格分開:
>>> str.split()
['hello', 'world']
>>>
D. python 正則表達式re.sub()提取字元串以及去除空格
Python 的re模塊提供了re.sub用於替換字元串中的匹配項。
語法:
re.sub(pattern, repl, string, count=0)
參數:
pattern : 正則中的模式字元串。
repl : 替換的字元串,也可為一個函數。
string : 要被查找替換的原始字元串。
count : 模式匹配後替換的最大次數,默認 0 表示替換所有的匹配。
實例:
註:re.sub(r'[a-zA-Z",:{}]', "", data),中括弧表示選擇其中的任意元素,a-zA-Z表示任意字母。
E. python 去除字元串中的空格
將字元串中的空格去除,字元串的長度就減少了,開始計算出的len(str)長度是原始字元串的長度,下標當然會越界
print'pleaseinputastring:'
string=raw_input('>')
string=string.replace('','')
printstring