[英]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.