简体   繁体   English

如果两个字符串的长度不相同,如何仅使用核心 python 3 一个接一个地连接字符串字符

[英]How to join string characters one by one if both string are not same in length using core python 3 only

I am beginner in python and i am working on a small task to join two string character by character without using any predefined function especially when string are not same in length我是 python 的初学者,我正在做一个小任务,在不使用任何预定义的 function 的情况下逐个字符地连接两个字符串,尤其是当字符串长度不相同时

for ex: s1 = 'MICROSOFT', s2 = 'CORPS' then output will be >> MC IO CR RP OS SOFT例如:s1 = 'MICROSOFT', s2 = 'CORPS' 那么 output 将是 >> MC IO CR RP OS SOFT

I have written below code我写了下面的代码

s1 = 'MICROSOFT'
s2 = 'CORPS'

for i in range(len(s1) and len(s2)):
    if len(s1)==len(s2):
       var = s1[i] + s2[i]
       print(var , end='')
    elif len(s1)!=len(s2):
        if len(s1)>len(s2):
           var1 = s1[i] + s2[i]
           print(var1, end=' ')

By using above code i have achieved output like this: MC IO CR RP OS通过使用上面的代码,我已经实现了这样的 output:MC IO CR RP OS

How i can print the last part ie SOFT??我如何打印最后一部分,即 SOFT?

You could do something like this after your loop你可以在循环后做这样的事情

s1 = 'MICROSOFT'
s2 = 'CORPS'

for i in range(len(s1) and len(s2)):
    if len(s1)==len(s2):
       var = s1[i] + s2[i]
       print(var , end='')
    elif len(s1)!=len(s2):
        if len(s1)>len(s2):
           var1 = s1[i] + s2[i]
           print(var1, end=' ')

if len(s1) > len(s2):
    print(s1[len(s2):])
elif len(s2) > len(s1):
    print(s2[len(s1):])

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

相关问题 在Python 2和3中获得相同的Unicode字符串长度? - Getting the same Unicode string length in both Python 2 and 3? 在Python中同时使用字符串和线程中的join() - Using join() from both string and threading at the same time in Python 如何在 Python 中将字符串列表加入一个字符串中 - How can I join a list of string into one string in Python 一个正则表达式如何仅匹配 Python 中字符串的前几个字符? - How would one Regex Match only the first few characters of a string in Python? Python3如何定义一个长度的字节串?(已解决) - Python3 how to define one length byte-string?(Solved) 如何在Python中从字符串中删除特殊字符(如“ / xC3”),同时保持相同长度的字符串 - How to remove special characters like “/xC3” from string in Python while keeping same length of string 如何拆分字符串并从python中的分隔字符串中只取一个 - How to split string and take only one from the separated string in python 如何在Python的字符串中仅保留一个已定义的子字符串 - How to leave only one defined sub-string in a string in Python Python:如何在一行中检查字符串中字符的出现 - Python: How to check characters occurrence in string in one line 如何在python中将2个字符交替添加到字符串中? - How would one alternately add 2 characters into a string in python?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM