在Python中从字符串中去除小写字母
str='www.wgoogle.cwm'
我需要把'.google'前面和后面的所有'w'都去掉。期望的结果是'.google'。
我试过用
str.replace('w','')
,但是没效果。有没有比这个更好的方法呢?现在,我需要把上面这个字符串中'.google'前后所有的小写字母都去掉。
我试过下面的方法,但都没有成功。
word='www.google.com' print re.sub('[a-z]','',word)
我该怎么做才能不写一个函数呢?
2 个回答
0
对于你的第一个问题,如果你把字符串 'www.wgoogle.cwm' 中的 'w' 去掉,前后都去掉,期望的结果应该是 '.wgoogle.cm'
str='www.wgoogle.cwm'
lst_str = str.split('.')
print(lst_str[0].replace('w','')+'.'+lst_str[1]+'.'+lst_str[2].replace('w',''))
我的输出是 .wgoogle.cm
但是如果你期望的结果是 .google.,那么可以使用下面的代码
str='www.wgoogle.cwm'
print('.'+str.split('.')[1].replace('w','')+'.')
输出将会是 .google.
1
如果你期待的是“.google.”,那么这些选项都不适用,但这个可能有效:
word='www.wgoowglew.cowm'
print '.' + word.split('.')[1].replace('w', '') + '.'