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?
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
Simply use isalnum()
and concatenate string
''.join([x for x in Data[0:4] if x.isalnum()]) + Data[4:]
#output
'15AN 4/41 45'
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.
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?
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
Simply use isalnum()
and concatenate string
''.join([x for x in Data[0:4] if x.isalnum()]) + Data[4:]
#output
'15AN 4/41 45'
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.