3 回答

TA贡献1873条经验 获得超9个赞
如果您考虑创建由破折号分隔的对,则可以使用以下函数:
def pair_div(string):
newString=str() #for storing the divided string
for i,s in enumerate(string):
if i%2!=0 and i<(len(string)-1): #we make sure the function divides every two chars but not the last character of string.
newString+=s+'-' #If it is the second member of pair, add a dash after it
else:
newString+=s #If not, just add the character
return(newString)
例如:
[In]:string="aazzxxcceewwqqbbvvaa"
[Out]:'aa-zz-xx-cc-ee-ww-qq-bb-vv-aa'
但是,如果您考虑将相同的字符分成一组并用破折号分隔,则最好使用正则表达式方法。

TA贡献1877条经验 获得超1个赞
如果您想将字符串分成 2 个字符的块,那么这将对您有所帮助。
import textwrap
s='aabbcc'
lst=textwrap.wrap(s,2)
print('-'.join(lst))
第二个属性定义了编号。您想要在特定组中的字符数
添加回答
举报