文章内容
2022/6/2 11:36:47,作 者: 黄兵
Python 字符串插入指定字符串
最近在处理一堆字符串的时候,需要对字符串指定的位置插入字符串,下面是示例:
原有字符串:405582
插入字符串后的结果:40-55-82
对于上面要求我们应该怎么实现呢?
我们可以使用循环,但是有些麻烦,下面是示例代码:
base_16_format = '405582'
base_16_format_list = list(base_16_format)
base_16_format_list.insert(2, '-')
base_16_format_list.insert(5, '-')
hex_format = ''.join(base_16_format_list)
上面首先将字符串转换为列表,然后使用列表的 .insert() 方法来插入字符。
关于 .join()
官方介绍如下:
S.join(iterable) -> str Return a string which is the concatenation of the strings in the iterable. The separator between elements is S.
.join()
方法中传递的参数需要是可迭代的,另外,是使用S作为可迭代参数的分割。 通过以上几点,我们可以这样理解: a.join(b)
,比如 b=123456,是可以迭代的。这个方法的作用就是把a插入到b中每个字符中。1a2a3a4a5a6就是输出。 ''.join([a, b])
是比较常见的用法。''是空字符,意味着在a, b之间加入空字符,也就是将a, b进行了连接。
这样就可以达到要求了。
参考资料:
黄兵个人博客原创。
转载请注明出处:黄兵个人博客 - Python 字符串插入指定字符串
itsdangerous.exc.BadTimeSignature: Signature b'pn2lywt7kfsyjnfyhhfunf33bra' does not match
异步加载 CSS 的最简单方法
异步加载 CSS 的最简单方法
评论列表