使用变量切片字符串

2024-06-16 17:56:09 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在制作一个python程序,在这里我需要检查变量的单个四个字母部分。例如,如果变量是help\u me\u code\u please它应该输出ease然后e\u pl等等,我用

a=0
b=3
repetitions=5
word="10011100110000111010"
for x in range (1,repetitions):        
    print(word[a:b])
    a=a+4
    b=b+4 

但是它只输出空行。 非常感谢您对我的帮助。你知道吗


Tags: in程序for字母helpcoderangeword
3条回答

对于转发:

[word[4*l:4*(l+1)] for l in range(0, int(len(word)/4)+1)]
['help', '_me_', 'code', '_ple', 'ase']

对于向后:

[word[::-1][4*l:4*(l+1)][::-1] for l in range(0, int(len(word)/4)+1)]
['ease', 'e_pl', '_cod', 'p_me', 'hel']

这是列表理解(https://docs.python.org/3.6/tutorial/datastructures.html#list-comprehensions),您可以迭代生成的列表。你知道吗

它的var[开始:结束:步进]。单词[::-1]的意思是获取一个字母,从开头开始,在结尾结束,然后前进-1步,所以它会反转字符串

对于新值:

word="10011100110000111010"
[word[4*l:4*(l+1)] for l in range(0, int(len(word)/4)+1)]
['1001', '1100', '1100', '0011', '1010']

[word[::-1][4*l:4*(l+1)] for l in range(0, int(len(word)/4)+1)]
['0101', '1100', '0011', '0011', '1001']

这应该起作用:

words = "help_me_code_please"
size = 4
start = len(words)%size - size

for i in reversed(range(start, len(words), size)):
    print(words[max(0,i):i+size])

输出为

ease
e_pl
_cod
p_me
hel

解释:start给了我们一个起点,即距离字符串(单词)长度的一些可整除块。在我们的例子中,它是-1,也就是说20 (5*4)远离19,长度是words。你知道吗

现在我们做一个反向循环,从大小为4的19 -> -1。我们开始15,11,7,3,-1。在每个循环中,我们从位置打印到位置+4。所以第一个循环迭代输出words[15:19],输出ease,第二个是words[11:15],依此类推。这就产生了我们看到的输出。你知道吗

希望这个解释有道理!你知道吗

假设你想用4个字的重复反印这个字。你知道吗

word = 'help_me_code_please'

# Looping from backwards on the word with a step of 4
for i in range(len(word)-1, -1, -4):
    # j is the starting point from where we have to print the string.
    j = i-3 if i > 3 else i-1
    print word[j:i+1]

相关问题 更多 >