Python:如何从字符串中提取字母或数字?

从字符串中提取字母

s = 'cn中国520'
print(''.join([i for i in s if i.encode('UTF-8').isalpha()]))

# 输出:cn

注意:中文的汉字会被 isalpha() 判定为 True,如果想区分中文和英文需要编码(encode('UTF-8'))后再调用 isalpha() 函数。

从字符串中提取数字

  • 方案一

    s = 'cn中国520'
    print(''.join([i for i in s if i.isdigit()]))
    
    # 输出:520
    

    注意:isdigit() 方法检测字符串是否只由数字组成,只对 0 和 正数有效。

  • 方案二

    s = 'cn中国520'
    print(''.join([i for i in s if i.isdecimal()]))
    
    # 输出:520
    

    注意:isdecimal() 方法检查字符串是否只包含十进制字符。这种方法只存在于unicode对象。

猜你喜欢

转载自blog.csdn.net/qq_34562959/article/details/127619897
今日推荐