如何过滤字符串中的'w','l',打印输出过滤后的字符串
for s in "HelloWorld":
for s in "HelloWorld":
if s not in ('w','l'):
print(s,'end='')
for s in "HelloWorld":
if s in ['w', 'l']:
continue
print(s, end='')
运行结果:
题目要求:写一个Python程序,判断一个字符串是否为回文字符串。 所谓回文字符串,即字符串的顺序和逆序完全相同,如字符串"ABCBA"、"ABCCBA"就是一个回文字符串,"ABCBAC"就不是。 注:不得使用reverse()方法或reversed()函数
代码如下:
o = input('请输入一字符串:')
w = int((len(o)+1)/2)
for i in range(w):
if o[i] == o[len(o)-1-i]:
s = 1
else:
s = 0
if s == 1:
print('这是一个回文字符串')
else:
print('这不是一个回文字符串')
部分运行结果如下:
问题回答:
字符串过滤功能可以通过Python内置函数和正则表达式实现。需要过滤掉的字符根据需求具体确定。
下面给出两种实现方式:
s = 'hello, 123 world!'
filtered_s = "".join(filter(lambda x: not x.isdigit() and not x in string.punctuation, s))
print(filtered_s) # 输出: hello world
import re
s = 'hello, 123 world!'
filtered_s = re.sub(r'[\d%s]' % re.escape(string.punctuation), '', s)
print(filtered_s) # 输出: hello world
其中,re.sub用法是将正则表达式所匹配的字符串替换为指定的字符串。 "." 代表任何字符 (换行符 \n 除外); "*" 代表0次或多次匹配前面的字符; "[]" 代表匹配 [] 中的字符; "\d" 代表匹配一个数字字符; "%s" 代表格式化一个元组或字典。
参考资料: