简体   繁体   English

从字符串 Python 的前 4 个值中删除字母数字以外的字符

[英]Remove characters other than alphanumeric from first 4 values of string Python

I need to remove characters other than alphanumeric from first 4 characters of string.我需要从字符串的前 4 个字符中删除字母数字以外的字符。 I figured out how to do it for the whole string but not sure how to process only the first 4 values.我想出了如何对整个字符串执行此操作,但不确定如何仅处理前 4 个值。

Data : '1/5AN 4/41 45'

Expected: '15AN 4/41 45'

Here is the code to remove the non-alphanumeric characters from string.这是从字符串中删除非字母数字字符的代码。

strValue = re.sub(r'[^A-Za-z0-9 ]+', '', strValue)

Any suggestions?有什么建议么?

Using string slicing is one possibility:使用字符串切片是一种可能性:

import re

strValue = '1/5AN 4/41 45'
strValue = re.sub(r'[^A-Za-z0-9 ]+', '', strValue[:4]) + strValue[4:]

print(strValue)

Outputs: 15AN 4/41 45输出: 15AN 4/41 45

Simply use isalnum() and concatenate string只需使用isalnum()并连接字符串

''.join([x for x in Data[0:4] if x.isalnum()]) + Data[4:]
#output 
'15AN 4/41 45'

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

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM