【问题标题】:How to insert white spaces between certain character positions, irrespective of what the character is?无论字符是什么,如何在某些字符位置之间插入空格?
【发布时间】:2019-09-22 08:59:27
【问题描述】:

该列称为 df['Col1']。如果列内字符数等于10,我想在每个字符串的第5和第6个字符之间添加2个空格,否则在第5和第6个字符之间只添加一个空格。

例如 RPYHVBN56I 变成 RPYHV__BN56I,任何字符多或少的字符串只输入一个空格,如 RPYHVBN56I00000 变成 RPYHV_BN56I00000

【问题讨论】:

    标签: python string


    【解决方案1】:

    你可以试试:

    df['Col1'] = df['Col1'].map(lambda s: s[:5] + ('  ' if len(s) == 10 else ' ') + s[5:])
    

    【讨论】:

    • 返回错误,'str'对象没有属性'str'?
    • 我已经编辑过了,为什么会出现这个错误?发生了什么?我还可以问 [:5] 我假设是指第五个字符吗?
    • @Sam s 因为单个值已经是字符串。当您想为整个series 调用字符串函数时,.str 是必需的。 [:5] 表示从开始到位置 5 的字符,例如 0-4 位置 - 前 5 个字符。
    • 完美。谢谢
    猜你喜欢
    • 1970-01-01
    • 2021-12-15
    • 2012-10-08
    • 1970-01-01
    • 1970-01-01
    • 2018-03-04
    • 2012-03-27
    • 2011-08-18
    相关资源
    最近更新 更多