用破折号 (-) python 分割字符串

我想得到一个字符串并将其分成由“-”分隔的部分。
输入:

aabbcc

和输出:

aa-bb-cc

有没有办法这样做?


犯罪嫌疑人X
浏览 248回答 3
3回答

眼眸繁星

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

冉冉说

如果您想将字符串分成 2 个字符的块,那么这将对您有所帮助。import textwraps='aabbcc'lst=textwrap.wrap(s,2)print('-'.join(lst))第二个属性定义了编号。您想要在特定组中的字符数
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python