【问题标题】:Is there a way of splitting a word into 3 different parts in python?有没有办法在python中将一个单词分成3个不同的部分?
【发布时间】:2022-01-04 19:41:31
【问题描述】:
char = "RV49CJ0AUTS172Y"

要获得此输出:

separated = "RV49C-J0AUT-S172Y"

我试过了:

split_strings = []
             n = 5
             for index in range(0, len(name), n):
                split_strings.append(name[index : index + n])

但这并没有如我所愿 This shows a good method but I want them on the same line with dashes between them

【问题讨论】:

  • 欢迎来到 StackOverflow,可以扩展拆分背后的逻辑吗?如果字符串的长度不能被 3 整除会怎样?
  • 您可以简单地使用:s[0:5] + "-" + s[5:10] + "-" + s[10:](将char 重命名为s,因为char 不是一个好的字符串名称)只要字符串是10-15 个字符长度。

标签: python string split


【解决方案1】:

您可以在一行中使用re

import re
string = "RV49CJ0AUTS172Y"

separated = "-".join(re.findall('.{%d}' % (len(string) / 3), string))

print(separated)

[输出]

RV49C-J0AUT-S172Y

【讨论】:

  • 这个答案的问题是:问题要求“3 个不同的部分”,而答案根本没有幻数 3。为什么这会给出 3 个部分?实际上这只是偶然,因为string 恰好有 15 个字符。这就是为什么我们得到follow-up questions
【解决方案2】:

您的代码几乎可以工作,只需计算所需的字符数 (n),而不是将其硬编码为 5。对于最终结果,使用 "-".join(...) 将数组的所有元素混合在一起形成一个单个字符串。

char = "RV49CJ0AUTS172Y"
split_strings = []
n = len(char) // 3
for index in range(0, len(char), n):
    split_strings.append(char[index: index + n])
print("-".join(split_strings))

【讨论】:

  • 这也可以,谢谢。
猜你喜欢
  • 1970-01-01
  • 2022-08-18
  • 2018-07-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-25
  • 2021-04-13
  • 1970-01-01
相关资源
最近更新 更多