在字符串包含奇数个字符时,如何在最后一个字符之后添加一个 ( _ ) 字符。

huangapple go评论95阅读模式
英文:

If the string contains an odd number of characters, how to add a ( _ ) character after the last character

问题

在最后一个字符后添加一个下划线(_)的方法是什么?

  1. def split_string(string: str) -> list:
  2. n = 2
  3. list1 = [string[i: i + n] for i in range(0, len(string), n)]
  4. return list1
  5. print(split_string("123456")) # ["12", "34", "56"]
  6. print(split_string("ab cd ef")) # ["ab", " c", "d ", "ef"]
  7. print(split_string("abc")) # ["ab", "c_"]
  8. print(split_string(" ")) # [" _"]
  9. print(split_string("")) # []
英文:

How to add a character(_) after the last character?

  1. def split_string(string: str) -> list:
  2. n = 2
  3. list1 = [string[i: i + n] for i in range(0, len(string), n)]
  4. return list1
  5. print(split_string("123456")) # ["12", "34", "56"]
  6. print(split_string("ab cd ef")) # ["ab", " c", "d ", "ef"]
  7. print(split_string("abc")) # ["ab", "c_"]
  8. print(split_string(" ")) # [" _"]
  9. print(split_string("")) # []

答案1

得分: 1

只需向临时副本添加一个字符,然后使用该字符进行操作:

  1. def split_string(string: str) -> list:
  2. s = string + "_" # <----
  3. list1 =
    展开收缩
    for i in range(0, len(string), 2)]
  4. # ^
  5. return list1
英文:

Just add a character to a temporary copy, and work with that:

  1. def split_string(string: str) -&gt; list:
  2. s = string + &quot;_&quot; # &lt;----
  3. list1 =
    展开收缩
    for i in range(0, len(string), 2)]
  4. # ^
  5. return list1

答案2

得分: 1

itertools 模块提供了 grouper 函数的定义:

  1. from itertools import zip_longest
  2. def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
  3. "将数据收集到非重叠的固定长度块中"
  4. # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
  5. # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
  6. # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
  7. args = [iter(iterable)] * n
  8. if incomplete == 'fill':
  9. return zip_longest(*args, fillvalue=fillvalue)
  10. if incomplete == 'strict':
  11. return zip(*args, strict=True)
  12. if incomplete == 'ignore':
  13. return zip(*args)
  14. else:
  15. raise ValueError('Expected fill, strict, or ignore')

你的函数是一个特殊情况:它将字符串分割成长度为2的组,使用“_”填充不完整的块,并将结果的2元组连接成单个字符串。

  1. def split_string(s):
  2. return list(map(''.join, grouper(s, 2, fillvalue="_")))
  3. # return [''.join(t) for t in grouper(s, 2, fillvalue="_")]
英文:

The itertools module provides the definition of a function grouper:

  1. from itertools import zip_longest
  2. def grouper(iterable, n, *, incomplete=&#39;fill&#39;, fillvalue=None):
  3. &quot;Collect data into non-overlapping fixed-length chunks or blocks&quot;
  4. # grouper(&#39;ABCDEFG&#39;, 3, fillvalue=&#39;x&#39;) --&gt; ABC DEF Gxx
  5. # grouper(&#39;ABCDEFG&#39;, 3, incomplete=&#39;strict&#39;) --&gt; ABC DEF ValueError
  6. # grouper(&#39;ABCDEFG&#39;, 3, incomplete=&#39;ignore&#39;) --&gt; ABC DEF
  7. args = [iter(iterable)] * n
  8. if incomplete == &#39;fill&#39;:
  9. return zip_longest(*args, fillvalue=fillvalue)
  10. if incomplete == &#39;strict&#39;:
  11. return zip(*args, strict=True)
  12. if incomplete == &#39;ignore&#39;:
  13. return zip(*args)
  14. else:
  15. raise ValueError(&#39;Expected fill, strict, or ignore&#39;)

Your function is a special case: you split your string into groups of 2, padding incomplete chunks with &quot;_&quot;, and joining the resulting 2-tuples back into a single string.

  1. def split_string(s):
  2. return list(map(&#39;&#39;.join, grouper(s, 2, fillvalue=&quot;_&quot;)))
  3. # return [&#39;&#39;.join(t) for t in grouper(s, 2, fillvalue=&quot;_&quot;)]

答案3

得分: 1

你可以在返回列表之前调整最后一个元素:

  1. if len(string) % 2:
  2. list1[-1] += "_"

或者支持其他值的 n

  1. if add := -len(string) % n:
  2. list1[-1] += "_" * add

或者,使用迭代器:

  1. def split_string(string: str) -> list:
  2. it = iter(string)
  3. return [c + next(it, "_") for c in it]
英文:

You could just adjust the last element before you return the list:

  1. if len(string) % 2:
  2. list1[-1] += &quot;_&quot;

Or to support other values of n:

  1. if add := -len(string) % n:
  2. list1[-1] += &quot;_&quot; * add

Alternatively, with an iterator:

  1. def split_string(string: str) -&gt; list:
  2. it = iter(string)
  3. return [c + next(it, &quot;_&quot;) for c in it]

huangapple
  • 本文由 发表于 2023年3月9日 23:14:46
  • 转载请务必保留本文链接:https://go.coder-hub.com/75686550.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定