如果可以的话,我想打印一个带有字符串中字母的“三角形”。如果我有“正确”一词,则输出应类似于
r
ri
rig
righ
right
我知道您使用一个没有索引的for循环遍历字符串
for i in string:
print(i)
或带有索引
for i in range(len(string)):
print(string[i])
但是我不确定如何将每个字母添加到下一行。
答案 0 :(得分:1)
在这里建立索引,以便将字符打印在第i
个索引上。您可以使用slicing [Pythoncentral]生成i
的列表(可能包括)。例如:
for i in range(len(string)):
print(string[:i+1])
请注意此处的冒号,这意味着我们将字符串切至(但不包括)第i
个索引。因此,string[:4]
将生成一个列表,该列表最多(但没有)索引4
。因此字符串的长度为4
。
答案 1 :(得分:1)
if len(ws._images) == 0:
# Initalise the `ref` data, do ws.add_image(...)
img = openpyxl.drawing.image.Image("myplot.png")
img.anchor='D50'
ws.add_image(img)
elif len(ws._images) == 1:
# Replace the first image do **only** the following:
ws._images[0] = openpyxl.drawing.image.Image("myplot.png")
# Update the default anchor `A1` to your needs
ws._images[0].anchor='D50'
else:
raise(ValueError, "Found more than 1 Image!")
public func cleanUpImages(zone2U:String) {
var records2Delete:[CKRecord.ID] = []
let zone2D = CKRecordZone(zoneName: zone2U)
let predicate = NSPredicate(value: true)
let query = CKQuery(recordType: remoteRecords.notificationMedia, predicate: predicate)
let operation = CKQueryOperation(query: query)
operation.recordFetchedBlock = { record in
records2Delete.append(record.recordID)
}
operation.queryCompletionBlock = { cursor, error in
print(records2Delete.count)
}
CKContainer.default().privateCloudDatabase.add(operation)
生成一对索引和元素。示例:
for index, c in enumerate(your_string, 1):
print(your_string[:index])
答案 2 :(得分:1)
s = 'right'
for i in range(1, len(s) + 1):
print(s[:i])
s [:1]表示您从头开始打印s中的所有字符