如何用手机号码中间的数字替换空间



我有一个带有列名称为"移动号"的数据框架。条目的空间在第六位的空间,最终有9位数字。

希望用数字(8(在第六位置替换空格,以使数字数字数。请建议。

在应用以下代码确保之前,在DF [" Mobile no"列中no'nan''和代码运行。在运行了df ["移动号"]后,装满了'Nan的df。看起来有些事情不起作用。

df["Mobile No"] = df["Mobile No"].str.replace('  ', ' ')
Sample number with space in '88888 8888'

如果需要替换所有EMPRT字符串使用s

#replace each space by value
df["Mobile No1"] = df["Mobile No"].str.replace(r's', '8')
#repalce consecutive spaces by one value
df["Mobile No2"] = df["Mobile No"].str.replace(r's+', '8')

如果需要在某个位置更换空白空间:

def replace_by_index(text, pos, replacement):
        return ''.join(text[:pos-1] + replacement + text[pos:]) if text[pos-1] == ' ' else text
df['Mobile No3'] = df['Mobile No'].apply(lambda x: replace_by_index(x, 6, '8'))
print (df)
     Mobile No   Mobile No1  Mobile No2   Mobile No3
0   08881 2889   0888182889  0888182889   0888182889
1   0881 28889   0881828889  0881828889   0881 28889
2  0888881  29  08888818829  0888881829  0888881  29

最新更新