本文介绍了交替换弦的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 说我有一个如下字符串: s1 =''hi_cat_bye_dog'' 和我想用'':''替换偶数''_''和用'''''取消偶数''_''',' 以便我得到一个如下所示的新字符串: s2 =''嗨:猫,再见:狗'' 有没有共同的方法可以做到这一点?我不能提出任何 解决方案... 提前谢谢 Cesco 解决方案 为了替换其他每一个,我倾向于使用模数,使用 计数器。 count = (如果你想要以0开头,那么就做1) /更换/在lalastring中: 如果计数%2 == 0: 甚至做 否则: 做奇数 算+ = 1 这是一种相当基本的方式,我相信人们会确保更有效的方式,但它通常适合我。 虽然我现在想知道当count == 2时是否计数%2是真的还是 false因为它返回0 当然你还需要做你的替换但你应该能够这样做。 如何拆分_,加入对与' ;:",最后加入 结果与, ? [''hi'',''cat'', ''bye'',''dog''] [''hi:cat'',''bye:dog''] ''嗨:猫,再见:狗'' (还有很多其他方法可以做到这一点,但上面的3线是短的,并且 直截了当。注意使用ra nge()跳过其他所有项目 在列表中) < / F> ''hi:cat,bye:dog'' 有很多。如果你想学习Python,不要害怕以啰嗦的方式(带循环和辅助函数)来写它 。 彼得 Hi, say I have a string like the following:s1 = ''hi_cat_bye_dog''and I want to replace the even ''_'' with '':'' and the odd ''_'' with '',''so that I get a new string like the following:s2 = ''hi:cat,bye:dog''Is there a common recipe to accomplish that? I can''t come up with anysolution... Thanks in advanceCesco 解决方案 For replacing every other one, I tend to use the modulo, with acounter. count = (if u want even start with 0 else do 1) while/for replacing /in lalastring:if count % 2 == 0:do evenelse:do oddcount += 1 This is a rather basic way of doing it, and I am sure people will suremuch more efficient ways, but it generally works for me. Though I am now wondering if count % 2 when count == 2 is true orfalse as it returns 0 Of course you still need to do your replace but you should be able todo that.how about splitting on "_", joining pairs with ":", and finally joiningthe result with "," ? [''hi'', ''cat'', ''bye'', ''dog''] [''hi:cat'', ''bye:dog''] ''hi:cat,bye:dog'' (there are many other ways to do it, but the above 3-liner is short andstraightforward. note the use of range() to step over every other itemin the list) </F> ''hi:cat,bye:dog'' There are many. If you want to learn Python don''t be afraid to write itin a long-winded way (with loops and helper functions) first. Peter 这篇关于交替换弦的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持! 10-21 11:58