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

标签 python python-3.x

我试图单独打印每个元素,这很好,但也会根据位置重复每个元素,例如。 "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

关于python - 根据位置多次打印字符串元素,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49436433/

相关文章:

python - 带有 if 语句的 Numpy 数组的功能

python - Django表单需要重新提交

python - 由于最新的python版本保留了dict的插入顺序,相等(==)的含义会改变吗?

Python S3 上传签名不匹配

python - asyncio 实际上是如何工作的?

列表上的 Python 连续操作以错误的顺序执行

python - 如何从 python 的 bin 文件夹中的脚本导入包/模块

python - 如何使用自定义用户从 Django 管理中的用户继承字段?

Python:从文件编辑 JSON 项目

sql-server - Python Turbodbc executemanycolumns 错误 : Unable to cast Python instance to C++ type (compile in debug mode for details)