Home > Software engineering >  Remove characters other than alphanumeric from first 4 values of string Python
Remove characters other than alphanumeric from first 4 values of string Python

Time:12-14

I need to remove characters other than alphanumeric from first 4 characters of string. I figured out how to do it for the whole string but not sure how to process only the first 4 values.

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?

CodePudding user response:

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

CodePudding user response:

Simply use isalnum() and concatenate string

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