You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python如何为表格中不足11位的手机号在固定位置补加数字9?

你可以在处理特殊字符前先通过正则匹配补全缺失的9,再做后续的格式统一操作,也可以在所有字符替换完成后通过长度判断兜底补全,修改后的代码如下:

# convert integer to string
dataNew = pd.DataFrame(data, columns=['Nome', 'Telefone Celular'])
dataNew['Nome'] = data['Nome'].str.split(" ").str[0].str.strip()
dataNew['Telefone Celular'] = data['Telefone Celular'].astype(str)

# 第一步:给右括号后缺9的号码补9,匹配(XX)XXXX-XXXX格式的号码
dataNew['Telefone Celular'] = dataNew['Telefone Celular'].str.replace(r"\)(\d{4}-)", r")9\1", regex=True)

# 后续原有格式处理逻辑
# 替换左括号为国家码55
dataNew['Telefone Celular'] = dataNew['Telefone Celular'].str.replace(r"\(", "55", regex=True)
# 移除右括号
dataNew['Telefone Celular'] = dataNew['Telefone Celular'].str.replace(r"\)", "", regex=True)
# 移除横杠
dataNew['Telefone Celular'] = dataNew['Telefone Celular'].str.replace("-", "", regex=True)

# 兜底校验:处理完所有字符后如果号码长度为12,说明仍缺9,在第4位(索引4)补9
# 正常号码长度为13:2位国家码+2位区号+9位手机号
dataNew['Telefone Celular'] = dataNew['Telefone Celular'].apply(lambda x: x[:4] + '9' + x[4:] if len(x) == 12 else x)

display(dataNew)

逻辑说明

  • 正则替换步骤会匹配所有右括号后仅跟着4位数字加横杠的10位手机号,直接在右括号后补9,覆盖你示例中的场景
  • 最后的长度校验作为兜底,避免特殊格式的号码漏补,只要最终处理后的号码长度不符合13位的标准,就自动补全缺失的9

内容的提问来源于stack exchange,提问作者user2916405

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.07 03:18:02