2016-08-18 158 views
0

例如,我有字符串s1 = "lets go to the mall" 和第二串s2 = "hello"如何操纵一个字符串等于另一个字符串的长度?

在Python,如何可以操纵s2串等于的s1长度。

s2那么会是什么样子:

s2 = "hellohellohellohell"这将具有相同的字符数为s1

+1

查看字符串乘法和切片。 – Carcigenicate

+0

python字符串是不可变的,所以你将不能在原地更改's2'。但是,您可以创建一个长度等于's1'的新字符串。 – Wajahat

回答

1

//是发现整个倍数的整数除法。 %是模(余)

s2我就可以进入s1然后用切片添加的s2剩余部分的次数。

s3 = s2 * (len(s1) // len(s2)) + s2[:(len(s1) % len(s2))] 

>>> s3 
'hellohellohellohell' 
4

下面是一个方法:

s1 = 'lets go to the mall' 
s2 = 'hello' 
s2 = ''.join(s2[i % len(s2)] for i in range(len(s1))) 
print(s2) # "hellohellohellohell" 

编辑:这是对于那些不熟悉Python或编程的解释=]

  • ''.join(...)需要一个迭代,这是可以遍历的东西,并将所有这些元素与空白字符串一起加入吐温。所以,如果里面的内容是一个可迭代的的字母,它会将所有这些字母连接在一起。
  • range(len(s1))产生可迭代的所有数字0len(s1) - 1。此迭代中的数字数量等于s1的长度。
  • s2[i]表示索引号为i的字符串s2中的字母。所以,如果s2 = 'hello',然后s2[0] = 'h's2[1] = 'e'
  • i % len(s2)意味着ilen(s2),或剩余当您的s2长度划分i
  • 因此,这些代码首先创建一个循环遍历s2多次的字母,以便获得多个字母,然后将它们连同它们之间的空字符串一起加入。
+1

迄今为止最干净的解决方案。 –

+0

而不是一次构建一个字母的字符串,一次构建一个's2'的副本,然后修剪多余的结尾。 ('len'(s1),len(s2)))[:len(s1)]'(这与其他一些答案相似)。 – chepner

+0

@chepner我认为这里的所有解决方案都有优点和缺点。对于这个解决方案,我想通过优化字符串连接和性能来提高可读性/清洁度。我认为其他解决方案可能会更快,但我发现这比分片方法更容易理解:) – Karin

0
(s2 * (len(s1)//len(s2) + 1))[:len(s1)] 
0

基本上乘以两个长度的math.floor分,然后添加字符串的其余s2

def extend(s1, s2): 
    return s2*int(math.floor(len(s1)/len(s2)))+s2[:len(s1) % len(s2)] 

>>> extend("lets go to the mall", "hello") 
'hellohellohellohell' 
>>> 
0

了我的头顶部,你必须原谅我,你可以使用这样的功能:

def string_until_whenever(s1, s2): 
i = len(s1) 
x = 0 
newstring = "" 
while i != 0: 
    newstring = newstring + s2[x] 
    x += 1 
    i -= 1 
    if x == len(s2) - 1: 
     x = 0 
return newstring 
0

效率低下,但很简单。 (乘法使得字符串比需要的长得多。)

n = len(s1) 
s3 = (s2*n)[:n] 
0

我认为有很多可能的解决方案。我的答案是:

s2 = s2*(len(s1)/len(s2)+1) 
s2 = s2[0:len(s1)] 
2

Itertools就是答案。更具体地说takewhilecycle

import itertools 

s1 = "lets go to the mall" 
s2 = "Hello" 

print ("".join(s for _, s in itertools.takewhile(lambda t: t[0] < len(s1), enumerate(itertools.cycle(s2))))) 

或者更简单(使用islice):

print ("".join(itertools.islice(itertools.cycle(s2)), len(s1))) 
0

未必是最干净的解决方案,但你也可以做到这一点,利用串乘法和字符串切片:

def string_until_whenever(s1, s2): 
    temp = ""  
    if len(s2) > len(s1): 
     temp = s2 
     s2 = s1 
     s1 = temp 

    new_string = "" 
    multiply_by = len(s1)/len(s2) 
    modulo = len(s1) % len(s2)  
    new_string = s2 * multiply_by 
    new_string = new_string + s2[0:modulo]  

    return new_string 


print(string_until_whenever("lets go to the mall", "hello")) 
#Outputs: hellohellohellohell 
相关问题