[英]Remove characters other than alphanumeric from first 4 values of string Python
我需要從字符串的前 4 個字符中刪除字母數字以外的字符。 我想出了如何對整個字符串執行此操作,但不確定如何僅處理前 4 個值。
Data : '1/5AN 4/41 45'
Expected: '15AN 4/41 45'
這是從字符串中刪除非字母數字字符的代碼。
strValue = re.sub(r'[^A-Za-z0-9 ]+', '', strValue)
有什么建議么?
使用字符串切片是一種可能性:
import re
strValue = '1/5AN 4/41 45'
strValue = re.sub(r'[^A-Za-z0-9 ]+', '', strValue[:4]) + strValue[4:]
print(strValue)
輸出: 15AN 4/41 45
只需使用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.