[英]Function that takes a string and returns a list of 8-character strings
I'm very new to programming. 我对编程很新。 I need to create a function that takes any string and a fill character and returns a list of 8 character strings. 我需要创建一个函数,它接受任何字符串和填充字符,并返回8个字符串的列表。 For example: 例如:
>>>segmentString("Hello, World!","-")
['Hello, W', 'orld!---']
As you can see, the string has 13 characters. 如您所见,该字符串有13个字符。 The function splits into 2 strings, where the first contains 8 characters, and the second contains 5 characters and 3 fill characters. 该函数分为2个字符串,第一个包含8个字符,第二个包含5个字符和3个填充字符。
So far, I've figured out how to do this for strings less than 8 characters, but not for more than 8 characters, where the string is split up, which is what I am stuck on. 到目前为止,我已经想出了如何为少于8个字符的字符串执行此操作,但不会超过8个字符,其中字符串被拆分,这是我坚持的。
def segmentString(s1,x):
while len(s1)<8:
s1+=x
return s1
How do you split a string up? 你如何拆分字符串?
You can use a slightly modified version of this chunking recipe : 您可以使用此分块配方的略微修改版本:
def chunks(L, n, char):
for i in range(0, len(L), n):
yield L[i:i + n].ljust(n, char)
res = list(chunks('Hello, World!', 8, '-'))
['Hello, W', 'orld!---']
A slightly modified version of @jpp's answer is to first pad the string with your fill character, so that the length is cleanly divisible by 8: @jpp的答案略微修改后的版本是首先使用填充字符填充字符串,以便长度可以被8完全整除:
def segmentString(s, c):
s = s + c * (8 - len(s) % 8)
return [s[i:i+8] for i in range(0, len(s), 8)]
>>> segmentString("Hello, World!","-")
['Hello, W', 'orld!---']
And if you needed the size to be variable, you can just add in a size argument: 如果您需要大小可变,您只需添加一个size参数:
def segmentString(s, c, size):
s = s + c * (size - len(s) % size)
return [s[i:i+size] for i in range(0,len(s),size)]
>>> segmentString("Hello, World!","-",4)
['Hell', 'o, W', 'orld', '!---']
Yet another possibility: 另一种可能性:
def segmentString(s1, x):
ret_list = []
while len(s1) > 8:
ret_list.append(s1[:8])
s1 = s1[8:]
if len(s1) > 0:
ret_list.append(s1 + x*(8-len(s1)))
return ret_list
I am also new to programming but I think you could use this... 我也是编程的新手,但我想你可以用这个...
Word = "Hello, World!---"
print([Word[i:i+x] for i in range(0, len(Word), x)])
Just change x to whatever value you want.. Check out https://www.google.co.in/amp/s/www.geeksforgeeks.org/python-string-split/amp/ Hope it helps. 只需将x更改为您想要的任何值。请查看https://www.google.co.in/amp/s/www.geeksforgeeks.org/python-string-split/amp/希望它有所帮助。
Here is the simple answer that you can understand that solves your problem with few simple ifs: 这是一个简单的答案,你可以理解,用几个简单的ifs解决你的问题:
a= 'abcdefghijklmdddn'
def segmentString(stuff):
c=[]
i=0
hold=""
for letter in stuff:
i+=1
hold+=letter
if i%8==0:
c.append(hold)
hold=""
c.append(hold)
if hold=="":
print(c)
else:
if hold==c[-1]:
print(c)
else:
c.append(hold)
print(c)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.