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

Question:

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?

Asked By: Pravin

||

Answers:

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

Answered By: Tzane

Simply use isalnum() and concatenate string

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

To remove non-alphanumeric characters in python use this:

import re                                                                     
string = re.sub(r'[^a-zA-Z0-9]', "", string)

re means regex/regular expressions.

Answered By: Ojijo
Categories: questions Tags: ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.