在迭代中大写字符,就像python中的字幕一样

2024-05-12 02:57:53 发布

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

所以我在youtube上看到一个视频,这个人在用一种叫做metasploit的东西。每次加载程序时,都会出现一个欢迎屏幕。每个字符都大写,就像一个从左到右的波浪,就像一个选框函数。你知道吗

作为一个python noob,我认为这很容易重新创建:)但是boi是我错了!你知道吗

这就是我得到的:

import time
import os

string = "this is a test"

count = 0
kuk = list(string)
for i in range(len(string)):
    os.system('clear')
    if i == count:
        string[i].upper()
    print(string)
    count += 1
    time.sleep(0.3)

问题似乎是我不知道如何迭代kuk变量,并像字符串一样打印列表(如果有意义的话),同时在每次迭代时将char操作为upper()。你知道吗

预期结果应为:

第一次迭代:这是一个测试

第二:这是一个测试

第三:这是一个测试

第四:这是一个测试

。。。。你知道吗


Tags: import程序string视频屏幕timeyoutubeos
3条回答

可以将生成器函数与enumerate结合使用:

string = "this is a test"

def marquee(some_string):
    for idx, char in enumerate(some_string):
        yield some_string[0:idx] + char.upper() + some_string[idx + 1:]

for s in marquee(string):
    print(s)

这就产生了

This is a test
tHis is a test
thIs is a test
thiS is a test
this is a test
this Is a test
this iS a test
this is a test
this is A test
this is a test
this is a Test
this is a tEst
this is a teSt
this is a tesT

最简单的方法是跟踪要大写的索引,并分三个阶段打印:

  1. 字符串中之前要大写的部分
  2. 要大写的字符,已转换为大写
  3. 字符串中要大写的后面的部分

我们可以用细绳切片来做这个。你知道吗

import os, time
string = "this is a test"
count = 0
while True:
   # clear screen
   os.system('clear')
   # print each of the three section
   first_part = string[:count]
   second_part = string[count].upper()
   third_part = string[count + 1:]
   print(first_part + second_part + third_part)
   # increment to the next index. Once we reach the end of the string, wrap around.
   count = (count + 1) % len(string)
   time.sleep(0.1)

使用sys.stdout.write回车\r(允许就地覆盖当前行)和enumerate功能的短进近:

import time
from sys import stdout

string = "this is a test"
for i, c in enumerate(string):
    if c:
        stdout.write('\r' + string[:i] + c.upper() + string[i+1:])
    time.sleep(0.3)
  • if c:条件允许跳过对空白字符的冗余切片和索引
  • 如果您使用的是Python>;=3.6,那么可以使用灵活的f-string样式来构建当前打印的行:stdout.write(f'\r{string[:i]}{c.upper()}{string[i+1:]}')

相关问题 更多 >