简体   繁体   English

如何检查字符串是否包含字母?

[英]How to check if a string contains letters?

I have a numerical string which sometimes it contains letters.我有一个数字字符串,有时它包含字母。 I must delete letters and everything after that from my input string.我必须从我的输入字符串中删除字母和之后的所有内容。 I have tried:我试过了:

import re
b = re.split('[a-z]|[A-Z]', a)
b = b[0]

But this returns error whenever the string doesn't contain letters.但是只要字符串不包含字母,就会返回错误。

Do I need to check if a contains letters before trying to split at their point?在尝试拆分之前,我是否需要检查a包含字母?

How can I check that ?我该如何检查

Two examples:两个例子:

a = '1234' 

and

a = '1234h'

I want to have b = '1234' after both我想在两者之后都有b = '1234'


Another example:另一个例子:
I want a= '4/200, 3500/ 500 h3m' or a= '4/200, 3500/ 500h3m' to return something like:我想要a= '4/200, 3500/ 500 h3m'a= '4/200, 3500/ 500h3m'返回如下内容:

b= ['4', '200', '3500', '500']
import re
match = re.search('^[\d]+', '1234h')
if match:
    print(match.group(0))

It will return '1234' for '1234' and '1234h'.它将为“1234”和“1234h”返回“1234 ”。 It find series of digits after starting and ignores after letter.它在开始后找到一系列数字,并在字母后忽略。

list = ['1234abc' , '5278', 'abc58586']

def range_sanitizer(s, lower_bound, upper_bound):
    return ''.join([x for x in s if lower_bound < x < upper_bound])

def remove_non_digits(s):
    return range_sanitizer(s, '0', '9')

def sanitize_list(list, sanitizer=remove_non_digits):
    return [sanitizer(item) for item in list]

if '__main__' == __name__:
    sanitized_list=sanitize_list(list)

    # ['1234', '5278', '58586']
    print(sanitized_list)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 如何检查字符串是否只包含字母? - How to check if a string only contains letters? 如何检查字符串是否包含字母或字母和撇号但是没有数字? - How to check if a string contains letters or letters and an apostrophe but NO numbers? 如何检查字符串是否仅包含大写或小写字母? - How can I check if a string only contains uppercase or lowercase letters? 如何检查字符串是否严格包含字母和数字 - How to check if a string is strictly contains both letters and numbers 如何检查一个字符串是否只包含小写字母和数字? - how to check if a string contains only lower case letters and numbers? 如何检查字符串是否包含字母表中的任何字母? - How can I check if a string contains ANY letters from the alphabet? 如何检查字符串是否包含python中的所有字母? - How do I check if a string contains ALL letters of the alphabet in python? 如何检查输入字符串是否包含特定字母并且在 Python 中是否可被 3 整除 - How to check if input string contains specific letters and is divisible by 3 in Python Python 3.6 如何检查一个列表是否包含一个带字母的字符串并且还包含一个整数? - Python 3.6 how to check to see if a list contains a string with letters and also contains an integer? 如何检查子字符串是否包含“苹果”中的所有字母 - How to check if a substring contains all of the letters in “apple”
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM