例如,我有字符串s1 = "lets go to the mall"
和第二串s2 = "hello"
如何操纵一个字符串等于另一个字符串的长度?
在Python,如何可以操纵s2
串等于的s1
长度。
s2
那么会是什么样子:
s2 = "hellohellohellohell"
这将具有相同的字符数为s1
。
例如,我有字符串s1 = "lets go to the mall"
和第二串s2 = "hello"
如何操纵一个字符串等于另一个字符串的长度?
在Python,如何可以操纵s2
串等于的s1
长度。
s2
那么会是什么样子:
s2 = "hellohellohellohell"
这将具有相同的字符数为s1
。
//
是发现整个倍数的整数除法。 %
是模(余)
乘s2
我就可以进入s1
然后用切片添加的s2
剩余部分的次数。
s3 = s2 * (len(s1) // len(s2)) + s2[:(len(s1) % len(s2))]
>>> s3
'hellohellohellohell'
下面是一个方法:
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))
产生可迭代的所有数字0
至len(s1) - 1
。此迭代中的数字数量等于s1
的长度。s2[i]
表示索引号为i
的字符串s2
中的字母。所以,如果s2 = 'hello'
,然后s2[0] = 'h'
,s2[1] = 'e'
等i % len(s2)
意味着i
模len(s2)
,或剩余当您的s2
长度划分i
。s2
多次的字母,以便获得多个字母,然后将它们连同它们之间的空字符串一起加入。(s2 * (len(s1)//len(s2) + 1))[:len(s1)]
基本上乘以两个长度的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'
>>>
了我的头顶部,你必须原谅我,你可以使用这样的功能:
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
效率低下,但很简单。 (乘法使得字符串比需要的长得多。)
n = len(s1)
s3 = (s2*n)[:n]
我认为有很多可能的解决方案。我的答案是:
s2 = s2*(len(s1)/len(s2)+1)
s2 = s2[0:len(s1)]
未必是最干净的解决方案,但你也可以做到这一点,利用串乘法和字符串切片:
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
查看字符串乘法和切片。 – Carcigenicate
python字符串是不可变的,所以你将不能在原地更改's2'。但是,您可以创建一个长度等于's1'的新字符串。 – Wajahat