Skip to main content
 首页 » 编程设计

python之根据位置多次打印字符串元素

2025年01月19日21arxive

我试图单独打印每个元素,这很好,但也会根据位置重复每个元素,例如。 "abcd"= A-Bb-Ccc-Dddd 等

所以我的问题是让 print 语句根据它们在字符串中的位置打印 x 次。我尝试了一些使用 len 和 range 的组合,但我经常遇到错误,因为我使用的是字符串而不是整数。

我应该在这里使用 len 和 range 吗?如果你们没有发布完成的代码,我更希望基本上只是如何解决该特定问题(如果可能的话),这样我仍然可以自己解决问题。

user_string = input() 
 
def accum(s): 
    for letter in s: 
        pos = s[0] 
        print(letter.title()) 
        pos = s[0 + 1] 
 
accum(user_string) 

请您参考如下方法:

您可以枚举可迭代对象(列表、字符串、范围、dictkeys...)——它提供索引和值:

text = "abcdef" 
for idx,c in enumerate(text):         
    print(idx,c) 

输出:

(0, 'a') 
(1, 'b') 
(2, 'c') 
(3, 'd') 
(4, 'e') 
(5, 'f') 

您可以使用它多次打印某些内容。打印命令有 2 个可选参数:

print("Bla","blubb", sep=" --->", end=" Kawumm\n") 

输出:

Bla --->blubb Kawumm 

指定输出之间和输出末尾打印的内容 - 您可以指定 end="" - 这样您就可以在同一行上继续打印。

独库:


编辑:

user_string = input()  
 
def accum(s): 
    t = []  # list to store stuff into 
    for count, letter in enumerate(s):  
        total = letter.upper() + letter * (count) # 1st as Upper, rest as is 
        t.append(total)  # add to list 
    print(*t, sep="-")   # the * "unpacks" the list into its parts 
 
accum(user_string) 

解包:

print( [1,2,3,4,5], sep=" +++ ")  # its just 1 value to print, no sep needed 
print(*[1,2,3,4,5], sep=" +++ ")  # 5 values to print, sep needed  

输出:

[1, 2, 3, 4, 5]  
1 +++ 2 +++ 3 +++ 4 +++ 5