字符串去除数字间的逗号
在西文数字的表示中,很多格式是类似这样:123,456,789。
如果得到这样的一个字符串,直接用int转换成整型肯定报错,那么在格式转换前需要先去除数字之间的逗号 。
如果字符串只有数字和“,”,那么可以用一个replace替换。
例如:
1
2
3
4
|
>>> n = '123,456,789' >>> n1 = n.replace( ',' ,'') >>> print n1 123456789 |
但是,如果当字符串中包括数字和其他字符,replace替换就有点霸道了。例如:Today is Sunday, I bought $ 100,000. 直接用replace替换会把字符串中的逗号标点符号也删除了。
所以需要找到 数字,数字 这种格式之前的逗号。
代码类似如下:
1
2
3
4
5
6
7
8
9
10
11
12
|
import re s = 'Today is Sunday, I bought $ 100,000.' p = re. compile (r '\d,\d' ) while 1 : m = p.search(s) if m: mm = m.group() s = s.replace(mm,mm.replace( ',' ,'')) else : break print s |
用正则表达式判断。
删除字符串中的符号
删除字符串中的指定符号
1
2
3
4
|
s = "abc123,123。" # 删除逗号 s = s.replace( ',' , '') print (s) # "abc123123。" |
删除字符串中的空格
1
2
3
4
5
6
7
8
9
|
s = " 123abc " # 删除开头的空格 print (s.lstrip()) # "123 abc " # 删除结尾的空格 print (s.rstrip()) # " 123 abc" # 删除开头和结尾的空格 print (s.strip()) # "123 abc" # 删除字符串中所有的空格 print (s.replace( ' ' , '')) # "123abc" |
删除字符串中的所有符号,只保留数字和英文字母
1
2
3
4
5
|
import re s = "123,abc .?/&?》^_^dddA。" # 把所有编码非\u0030-\u0039(数字)、\u0041-\u007a(英文字母)的字符替换为空字符串 rs = re.sub( "([^\u0030-\u0039\u0041-\u007a])" , '', s) print (rs) # "123abcdddA" |
只字符串中的保留汉字
1
2
3
4
5
|
import re s = "我爱中国
延伸 · 阅读
精彩推荐
|