#习题1:一个句子中的所有数字和标点符号删除
def delete_num_punctuation(s): import string for i in s: if i in string.punctuation:#判断是否有标点,是的话替换掉 s=s.replace(i," ") s=s.split() result =[] for i in s: if not i.isdigit():#用isdigit函数判断是否数字 result.append(i) return " ".join(result)
s="I am 15 years old!" print(delete_num_punctuation(s))
C:\Users\dell>py -3 C:\Users\dell\Desktop\练习\5\0503.py
I am years old
代码优化:
#上述代码两次遍历字符串,可以优化写在一起,最后直接拼接
s="I am 15 years old!" def delete_num_punctuation(s): import string str ="" for i in s: if not i.isdigit() and i not in string.punctuation: str +=i return str print(delete_num_punctuation(s))
#习题2:自定义实现strip()
Python strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。
strip()方法语法:
str.strip([chars])
s=" abc d \n" result ="" for i in s: if i not in ["\r","\n","\t"," "]: result +=i print(result)
#习题3:自定义实现str.upper()
Python upper() 方法将字符串中的小写字母转为大写字母。
upper()方法语法:
str.upper()
s="hdka"
str_result =""
for i in s:
if i>=chr(ord('a')) and i<=chr(ord('z')):
str_result +=chr(ord(i)-32)
else:
str_result +=i
str_result =""
for i in s:
if i>=chr(ord('a')) and i<=chr(ord('z')):
str_result +=chr(ord(i)-32)
else:
str_result +=i
print(str_result)
#习题4:自定义实现str.lower()
s="FHSJKakaae" str_result ="" for i in s: if i>=chr(ord('A')) and i<=chr(ord('Z')): str_result +=chr(ord(i)+32) else: str_result +=i print(str_result)