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

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

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

问题

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

def split_string(string: str) -> list:
    n = 2
    list1 = [string[i: i + n] for i in range(0, len(string), n)]
    return list1

print(split_string("123456"))  # ["12", "34", "56"]
print(split_string("ab cd ef"))  # ["ab", " c", "d ", "ef"]
print(split_string("abc"))  # ["ab", "c_"]
print(split_string(" "))  # [" _"]
print(split_string(""))  # []
英文:

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

def split_string(string: str) -> list:
    n = 2
    list1 = [string[i: i + n] for i in range(0, len(string), n)]
    return list1


print(split_string("123456"))  # ["12", "34", "56"]
print(split_string("ab cd ef"))  # ["ab", " c", "d ", "ef"]
print(split_string("abc"))  # ["ab", "c_"]
print(split_string(" "))  # [" _"]
print(split_string(""))  # []

答案1

得分: 1

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

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

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

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

答案2

得分: 1

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

from itertools import zip_longest

def grouper(iterable, n, *, incomplete='fill', fillvalue=None):
    "将数据收集到非重叠的固定长度块中"
    # grouper('ABCDEFG', 3, fillvalue='x') --> ABC DEF Gxx
    # grouper('ABCDEFG', 3, incomplete='strict') --> ABC DEF ValueError
    # grouper('ABCDEFG', 3, incomplete='ignore') --> ABC DEF
    args = [iter(iterable)] * n
    if incomplete == 'fill':
        return zip_longest(*args, fillvalue=fillvalue)
    if incomplete == 'strict':
        return zip(*args, strict=True)
    if incomplete == 'ignore':
        return zip(*args)
    else:
        raise ValueError('Expected fill, strict, or ignore')

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

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

The itertools module provides the definition of a function grouper:

from itertools import zip_longest


def grouper(iterable, n, *, incomplete=&#39;fill&#39;, fillvalue=None):
    &quot;Collect data into non-overlapping fixed-length chunks or blocks&quot;
    # grouper(&#39;ABCDEFG&#39;, 3, fillvalue=&#39;x&#39;) --&gt; ABC DEF Gxx
    # grouper(&#39;ABCDEFG&#39;, 3, incomplete=&#39;strict&#39;) --&gt; ABC DEF ValueError
    # grouper(&#39;ABCDEFG&#39;, 3, incomplete=&#39;ignore&#39;) --&gt; ABC DEF
    args = [iter(iterable)] * n
    if incomplete == &#39;fill&#39;:
        return zip_longest(*args, fillvalue=fillvalue)
    if incomplete == &#39;strict&#39;:
        return zip(*args, strict=True)
    if incomplete == &#39;ignore&#39;:
        return zip(*args)
    else:
        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.

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

答案3

得分: 1

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

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

或者支持其他值的 n

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

或者,使用迭代器:

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

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

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

Or to support other values of n:

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

Alternatively, with an iterator:

def split_string(string: str) -&gt; list:
    it = iter(string)
    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:

确定