可以使用字符串的strip()方法去除字符串两侧的空格,再使用isdigit()方法判断是否为数字,最后使用字符串切片将数字去除。

代码如下:

test_str = "02101 Hello Python 10310"
test_str = test_str.strip()  # 去除两侧空格
for i in range(len(test_str)):
    if not test_str[i].isdigit():  # 判断是否为数字
        test_str = test_str[i:]
        break
test_str = test_str.strip()  # 再次去除两侧空格
print(test_str)

输出结果为:

Hello Python
用python 设定字符串test_str=02101 Hello Python 10310去掉test_str中两侧的数字和空格后输出。

原文地址: https://www.cveoy.top/t/topic/ceCD 著作权归作者所有。请勿转载和采集!

免费AI点我,无需注册和登录