Python简介,第2章–字符串和列表

本文介绍了Python中的字符串和列表基础知识,包括连接、扩展、索引、切片等操作。故事背景是一个名为Baldric的角色在梦境中与叛军领袖Cassandra交流,学习如何利用这些概念来解决问题。通过实际例子展示了如何在实际场景中应用Python的字符串和列表操作。
摘要由CSDN通过智能技术生成


Something was really bothering Baldric about 106479825301.0, the answer to the mysterious request he’d received. Sitting down at his desk after enduring his meeting with Kevin, he realized what it was. If you only looked at the answer’s whole number portion…

小号 omething是真正困扰佩饰约106479825301.0,回答他收到神秘的请求。 在与凯文(Kevin)会面后,他坐在办公桌旁,他意识到那是事实。 如果您只看答案的整数部分…

>>> int(106479825301.0)
106479825301

…then every number from 0 to 10 appeared exactly once in the larger number’s digits.

…然后,从0到10的每个数字都会在较大的数字中恰好出现一次。

“Huh, that’s weird. Well, whatever that means, it’s got nothing to do with me, that’s for sure. No sir, I’d rather be a hobgoblin dentist than poke my nose into Management’s affairs. Not curious at all. Nope.”

“嗯,那很奇怪。 好吧,这意味着什么,与我无关,这是肯定的。 不,先生,我宁愿成为一名妖精牙医,也不愿对管理层的事务nose之以鼻。 一点也不好奇。 不。”

After a moment more of staring at the number in silence, Baldric shrugged and proceeded to surreptitiously study a page from a music theory book he’d swiped from the library years ago. This was the most dangerous book he could bring himself to sneak into work. He had worse hidden at home.

过了一会儿,他默默地盯着那个数字,鲍德瑞克耸了耸肩,然后秘密地研究了他几年前从图书馆借来的一本音乐理论书的一页。 这是他可以潜入工作中的最危险的书。 他在家里藏得更糟。

Around 10pm, when one was permitted, if not encouraged, to leave the office, Baldric was about to get up and walk home when something caught his ear. A couple of clerks were having a hushed conversation in the hall just outside his cubicle, and he could have sworn he’d heard the word “rebel”. He sat still, pretending to read.

晚上10点左右,当有人允许(如果不鼓励的话)离开办公室时,鲍德瑞克(Baldric)刚起床就走了,回家时听到了什么声音。 几名店员在小隔间外面的大厅里安静地交谈着,他可能发誓他听到过“反叛”一词。 他坐着不动,假装读书。

“A rebel leader, huh?”

“叛军领袖,是吗?”

“Yeah, goes by the name of Cassandra. Apparently they caught her in some kind of ambush.”

“是的,以卡桑德拉(Cassandra)的名字命名。 显然他们把她困在了某种埋伏之中。”

The clerk that had just spoken paused for a moment, then lowered his voice. Baldric slowly stood up and crept closer to the conversation, straining to hear.

刚刚讲过话的店员停了片刻,然后放低了声音。 鲍德瑞克慢慢站起来,悄悄地走近了谈话,不知所措。

“You didn’t hear this from me, but supposedly she froze half a legion in their tracks, turned ’em to ice cubes with this magic of hers before they took her down.”

“你没有从我这里听到这些,但是据推测,她冻结了他们军队中的半个军团,在他们把她击倒之前,用她的魔法把它们变成了冰块。”

“Mother’s beard, sounds like my kind of gal,” Baldric thought to himself. “That’s of course if she wasn’t a rebel. No, zero interest in that kind of person. I’d better take note of her name though…just so I can make sure to stay away from her, in case we meet by accident or something.” To record the rebel’s name, Baldric began to weave new patterns he had read about in the Book of Magic.

“母亲的胡须,听起来像是我的女孩,”鲍德瑞克心想。 “如果她不是叛军,那当然是。 不,对这种人的兴趣为零。 不过,我最好记下她的名字……只是为了确保我们可以不离她,以防万一我们偶然相遇。” 为了记录起义军的名字,鲍德瑞克开始编织他在《魔法书》中读到的新图案。

>>> rebel_name = 'Cassandra'
>>> rebel_name
'Cassandra'

# you can also use double quotes, >>> rebel = "Cassandra"

He could tell this magic was something altogether different from integers and floats and quickly investigated.

他可以说出这种魔术完全不同于整数和浮点数,并很快进行了研究。

>>> type(rebel_name)
<class 'str'>

# str is short for string, a sequence of characters surrounded by quotes
# strings can include letters, numbers, spaces, and other keyboard characters

# you can convert other things into strings using str()
>>> str(2)
'2'

>>> str(2.0)
'2.0'

# you can also convert certain strings to numbers
>>> int('2')
2

>>> float('2')
2.0

# but not just any string can be a number
>>> int("mother's beard")
Traceback (most recent call last):
  File "python", line 1, in 
ValueError: invalid literal for int() with base 10: "mother's beard"

Interesting. But the clerks weren’t finished speaking.

有趣。 但是店员还没说完。

“From what I hear, they’ve got her on display at the Teleportation Circle.”

“据我所知,他们在瞬移传送带上展出了她。”

“They didn’t Fire her yet?”

“他们还没有解雇她?”

“Well, technically they have to Hire her first, and you know how the paperwork is. But I heard she’s scheduled for Firing first thing in the morning.”

“嗯,从技术上讲,他们必须首先雇用她,而且您知道文书工作的情况。 但是我听说她预定早上开火。”

The subject changed, and Baldric decided to slip out. He wanted to see if he could find this pre-burnt-at-stake rebel and still get some sleep before the looming 5am daily start time. It had been easy avoiding unwanted conversations on the way out of the office recently, as many employees were out sick. A significant majority, in fact. Everyone apparently had the same nasty cold. Even Bill from Accounting was out sick, and previously he hadn’t left the office in 7 years! At least the place was quieter than usual.

话题变了,鲍德瑞克决定溜出去。 他想看看他是否可以找到这种事前准备的叛逆者,并且在迫在眉睫的每日凌晨5点开始时间之前仍能入睡。 由于许多员工生病了,最近很容易避免在离开办公室时进行不必要的交谈。 实际上,绝大多数。 显然每个人都感冒。 甚至来自Accounting的Bill都病了,以前他已经7年没离开办公室了! 至少这个地方比平时安静。

Just outside the office, posted to the only lit lantern pole on the street, Baldric saw a poster. He could just make out what it said in the moonlight.

在办公室外面,贴在街道上唯一一根点燃的灯笼杆上的鲍德瑞克看到了一张海报。 他可以说出月光下的声音。

CAPTURED: Cassandra Winterheart CRIMES: Inappropriate Use of Magic, Libel, Arson, Mass Murder, Rebellion, Overdue Books

捕获:Cassandra Winterheart犯罪:不当使用魔术,诽谤,纵火,群众谋杀,叛乱,逾期书籍

Come one, come all, to the Firing of the notorious rebel leader Cassandra Winterheart tomorrow at dawn. All Employees are permitted to attend.

一起来吧,一路走过来,明天黎明时向臭名昭著的反叛领导人卡桑德拉·温特哈特开火。 允许所有员工参加。

“Cassandra Winterheart. She’s a keeper for sure…I mean, they ought to keep her locked up for sure. I’d better update the name I recorded earlier though, just to be circumspect. Hmm…to add to a string, I seem to recall the Book saying you could use ‘+’ just like with numbers.”

“ Cassandra Winterheart。 她肯定是个看门人……我的意思是,他们应该确定把她锁起来。 不过,为了谨慎起见,我最好更新一下我之前记录的名称。 嗯……要添加到字符串中,我似乎想起了《圣经》说过,您可以像数字一样使用“ +”。”

>>> 'Cassandra' + 'Winterheart'
'CassandraWinterheart'

# try >>> 'Cassandra' + ' Winterheart'
# or >>> 'Cassandra' + ' ' + 'Winterheart'

“It worked! Though I need to remember the space. Since I already have her first name saved in the variable rebel_name, I’ll see if I can just add to that same variable.”

“有效! 虽然我需要记住空间。 由于我已经将她的名字保存在变量rebel_name中 ,所以我看看是否可以将其添加到相同的变量中。”

# variables containing strings can be added to as follows (try with numbers too)
>>> rebel_name = rebel_name + ' Winterheart'
>>> rebel_name
'Cassandra Winterheart'

# also try >>> rebel_name += ' Winterheart'

Baldric left the poster and began walking down the dimly-lit streets of the city in the direction of the Teleportation Circle. “Well, I guess I’ll just go for a walk to clear my head before I go home. No direction in particular. Just getting a little exercise, that’s all.” He noticed that, aside from a few guard patrols, the streets were deserted. There were more than a few rats about, but not a single person. Normally there’d be at least a little activity this time of night. Maybe everyone was getting a good night’s rest for the Firing tomorrow.

Baldric离开了海报,开始朝着Teleportation Circle的方向走在城市昏暗的街道上。 “好吧,我想我回家之前会散散步去清理我的头。 没有特别的指示。 只需做一点运动就可以了。” 他注意到,除了几个警卫巡逻队之外,街道还空无一人。 大约有多只老鼠,但没有一个人。 通常,这个晚上至少有一点活动。 也许明天明天每个人都可以睡个好觉。

Putting those thoughts out of his mind, Baldric experimented further with this new Magic of his.

将这些想法排除在外,鲍德瑞克(Baldric)进一步尝试了他的新魔术。

“So Magic can be used with not only numbers, but words too! I wonder if there’s anything else I can do with strings. Well, if addition works with strings, and all the basic arithmetical operators ( + , – , * , / ) worked with numbers, maybe all the other operators work on strings too.”

“所以魔术不仅可以用于数字,而且可以用于单词! 我想知道字符串是否还能做其他事情。 好吧,如果加法运算符适用于字符串,并且所有基本算术运算符(+,–,* * /)均适用于数字,那么也许其他所有运算符也适用于字符串。”

>>> rebel_name - ' is someone I hope I NEVER meet'
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'str'

>>> rebel_name * ' is someone I hope I NEVER meet'
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: cant multiply sequence by non-int of type 'str'

>>> rebel_name / ' is someone I hope I NEVER meet'
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'str'

"""
Text that looks like the results above indicates that some kind of 
error (aka 'exception') has occurred. In these cases, they are all TypeErrors.
The text after 'TypeError:' gives a description of the error.
The text above 'TypeError:' says where in the code the error occurred.
For now, don't worry too much about interpreting these messages.
Just know that they mean something in the code didn't quite work.
"""

# And this is a single line comment
# but the above paragraph is a multi-line comment (and string too), which is wrapped in triple quotes.
# To see that it can also be a string, try assigning the above multi-line comment to a variable.

Baldric’s weavings of Magic, instead of coalescing into a result, simply unraveled and faded away. “Well, that didn’t work. So I can at least combine strings to make longer strings. But what if I just want part of a string? Like, say, Cassandra’s initials? Maybe something like…”

鲍德瑞克(Baldric)的魔术编织,而不是凝聚成一个结果,只是解开并逐渐消失。 “嗯,那没用。 因此,我至少可以将字符串组合成更长的字符串。 但是,如果我只想要字符串的一部分怎么办? 例如,Cassandra的缩写? 也许像……”

>>> rebel_name[1]
'a'

“What happened there? Oh, I remember now, Magic starts most things counting from zero, not one. So to get the first character, I need to do…”

“那里发生了什么? 哦,我现在记得,魔术开始的大多数事情都是从零开始,而不是从一开始。 因此,要获得第一个角色,我需要做的……”

>>> rebel_name[0]
'C'

“And if I wanted the initials…”

“而且如果我想要缩写的话……”

>>> first_initial = rebel_name[0]
>>> last_initial = rebel_name[10]
>>> print(first_initial, last_initial)
C W

# try assigning both variables at once
# >>> first_initial, last_initial = rebel_name[0], rebel_name[10]

“That’s nice, but I’ll wager there’s a way I can select more than just one character from a string at a time. Actually, I think I remember how.”

“很好,但是我敢打赌,我可以一次从一个字符串中选择多个字符,而不是一个字符。 实际上,我想我还记得。”

>>> rebel_name[0:8]
'Cassandr'

“I see, so the 0th character is included in the slice, but the 8th character is not. So if I want all characters from index 0 to index 8, I need to do…”

“我知道,因此切片中包含第0个字符,但没有包含第8个字符。 因此,如果我希望从索引0到索引8的所有字符,我都需要做……”

>>> rebel_name[0:9]
'Cassandra'

# also try >>> rebel_name[:9]

“Perfect! I’ll store both names separately.”

“完善! 我将分别存储两个名称。”

>>> first_name, last_name = rebel_name[:9], rebel_name[10:]

>>> print(first_name, last_name)
Cassandra Winterheart

At this point, Baldric could just make out the top of HR’s facility over the rooftops to the northwest, a set of three inverted pyramids held aloft over an open pit of lava by a wild array of spindly stone pillars. The lava cast the the fortress in a deep red glow. But more menacing still was the Emperor’s Palace to the north, an impossibly high black stone fortress that loomed over the city like a gravestone over an ant colony.

在这一点上,鲍德瑞克(Baldric)刚好可以看出HR在西北部屋顶上的设施的顶部,这是由三个倒置的金字塔组成的一组金字塔,这些金字塔在高架的熔岩坑上方高高举起,上面是一排排乱石柱。 熔岩使堡垒散发出深红色的光芒。 但是,更具威胁性的仍然是北部的皇帝宫殿,这是一个不可能达到的高高的黑色石头堡垒,像一块蚂蚁殖民地上的墓碑一样笼罩着整个城市。

Baldic froze as he suddenly had a flashback to his dream last night. His recollection was foggy, but he remembered dark corridors, and a man, and a door, and…he was starting to recall more of the dream when something caught his eye high up in the sky. A faintly shimmering purple web spreading out over the city. He watched it in perplexion as it continued to expand, crisscrossing the sky as far as he could see.

Baldic僵住了,因为他昨晚突然回想起自己的梦想。 他的回忆是雾蒙蒙的,但他想起了黑暗的走廊,一个男人和一扇门,……当某事引起他的注意时,他开始回忆起更多的梦境。 淡淡的紫色网片散布在城市各处。 当它继续膨胀时,他困惑地看着它,尽其所能地穿越天空。

“What in the name of my father’s axe is that? Oh boy, yep, definitely another one of those things that is not my business. What mystical sky web? I don’t see anything. Maybe it’s time to head home.” He turned around and started walking, then paused to stare up at the sky for a moment more. Finally Baldric turned back around and continued determinedly in the direction he had been going. “I can get home just as fast taking this route. It’s more scenic anyways.” Walking along, he was soon lost in thought once again.

“那是我父亲的斧头的名字? 哦,男孩,是的,绝对不是我的事。 什么神秘的天空网? 我什么也没看到。 也许该回家了。” 他转身开始走动,然后停下来凝视着天空一会儿。 最终,鲍德瑞克转过身来,坚定地朝他前进的方向走。 “走这条路,我可以很快回到家。 无论如何,这更风景。” 一路走来,他很快又陷入了沉思。

“Hmm, so addition is the only operation that works with two strings. Something about that is bugging me…Aha! What if I use both strings and numbers together?”

“嗯,所以加法是唯一适用于两个字符串的操作。 那件事使我烦恼……啊哈! 如果我同时使用字符串和数字怎么办?”

>>> test_string = "Busyness is Progress!"

>>> test_string + 3
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: Cant convert 'int' object to str implicitly

>>> test_string - 3
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: unsupported operand type(s) for -: 'str' and 'int'

>>> test_string * 3
'Busyness is Progress!Busyness is Progress!Busyness is Progress!'
# Bingo!

>>> test_string / 3
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: unsupported operand type(s) for /: 'str' and 'int'

“Fascinating! So you can actually multiply strings and numbers together to form a longer string. But what if…”

“迷人! 因此,您实际上可以将字符串和数字相乘以形成更长的字符串。 但是,如果……”

Muttering to himself as he strolled along, Baldric half-consciously navigated the city streets. At one point he thought he heard something and stopped to look around. He had wandered into an alley with deep shadows and several nooks and crannies. Not seeing anyone, he continued on, more cautiously than before, when a putrid stench struck his nostrils. He was about to vomit, but had to focus on maintaining his balance as something wet caught his ankle. He heard a moan from behind, and turned to see a man stumbling towards him in the moonlight. Half the man’s face was missing.

当他漫步时,鲍德瑞克自言自语,半自觉地走过城市的街道。 有一次他以为他听到了什么,便停下来环顾四周。 他走进了一条幽暗的小巷,有几个角落和缝隙。 没有见到任何人,他继续,比以前更加谨慎,当腐臭的恶臭打到他的鼻Kong时。 他将要呕吐,但必须注意保持平衡,因为湿的东西缠住了脚踝。 他从背后听到一声mo吟,转身看到一个人在月光下绊向他。 该名男子的一半脸不见了。

Baldric fell over backwards in shock and landed in more of the smelly wet ropes. As the man staggered towards him, Baldric wished the man would go away, and found himself weaving threads of Magic, something other than Logic. A gust of wind burst towards the man, barely slowing him down for a moment. Baldric then focused on the man freezing in his tracks. A chilling mist descended on his assailant, ice crystallizing over him, but the man kept stumbling on. Scrambling backwards through more rubbish, Baldric frantically imagined a wall. The earth rose up in front of Baldric to form a knee-high rise which the man tripped over, but still he crawled onward, moaning and grasping for Baldric’s foot. Imagining the man’s destruction, Baldric channeled yet a different kind of Magic, and jets of flame erupted from Baldric’s outstretched hand. The man was enveloped by the flames and after a moment finally lay still, smoke rising from his charred corpse.

鲍德瑞克震惊地倒下,跌落在更多臭湿的绳子上。 当那个男人蹒跚地走向他时,Baldric希望那个男人走开,发现自己在编织魔术的线,这不是逻辑的东西。 一阵风吹向那个男人,几乎没有使他减速一会儿。 然后,鲍德瑞克专注于那个在自己的赛道上定格的人。 一股冷雾降在他的行凶者身上,冰晶在他身上结晶,但是那个人一直绊着脚步。 鲍德里克疯狂地想着一堵墙,向后乱扔垃圾。 大地在鲍德瑞克(Baldric)前面升起,形成了一个膝盖高的上升,该人绊倒了,但他仍然向前爬,,​​吟并抓住鲍德瑞克的脚。 想象着那个人的毁灭,鲍德瑞克传出了另一种魔法,鲍德瑞克伸出的手喷出了火焰。 该名男子被火焰笼罩,片刻后终于静止不动,烟从他烧焦的尸体中升起。

Panting heavily, Baldric stood up, trying to make sense of what had just happened. He was glad it was too dark to see what he had been crawling through. “Wow…okay. That was…something. Yeah. Of all the places in the world, who would’ve guessed that this was where I’d see my ex-wife again? And I guess I can shoot fire now? What a day. Anyways, I’d better be moving along. No telling how many more of those things there are, or what the city guards would make of the situation.”

Baldric喘着粗气气站起来,试图弄清刚刚发生的事情。 他很高兴天太黑了,看不到他一直在爬行。 “哇...好吧。 那是…某事。 是的 在世界上所有地方中,谁能想到这是我会再次见到前妻的地方? 我想我现在可以开枪? 真是一天 无论如何,我最好继续前进。 不知道还有多少这些东西,或者城市警卫队将如何处理这种情况。”

Still slightly in shock, Baldric continued on and soon found himself in a large, circular moonlit plaza. It looked like something was carved into the ground here, several rings of symbols apparently encircling the plaza, but they were hard to see in the darkness. He could, however, make out the three large statues spread evenly around the circle. Statues of sphinxes, as he recalled. “Uh oh, looks like I accidentally wandered over to the Teleportation Circle. Oh well, no harm done, I’ll just turn around and…” There was a wheeled cage in the center of the Circle containing a shadowy seated figure. It rose when it saw him and motioned him over.

仍然略为震惊,鲍德瑞克继续前进,不久便发现自己处于一个大型圆形月光广场中。 看起来好像是在这里的地面上刻了些东西,几个符号环显然环绕着广场,但是在黑暗中很难看到它们。 但是,他可以辨认出三个均匀分布在圆圈中的大雕像。 他回忆道,狮身人面像的雕像。 “哦,看来我不小心徘徊到了心灵传送带。 哦,好吧,没有伤害,我就转身……”圆环的中央有一个带轮子的笼子,里面笼罩着一个身影。 看到他并示意他过去时,它升起了。

“Pssst. Baldric, quickly, there isn’t much time!” it whispered.

“ Pssst。 秃头,很快,没有太多时间了!” 它低声说。

Baldric gasped. He glanced around, pondered running home one last time, then hurried over to the cage. Inside was a young elven woman in a gray prisoner’s garb. Beautiful, like a porcelain doll made flesh. She commanded an air of authority, however, and even in the darkness Baldric could tell she was a woman that expected to be obeyed. “Not my type at all actually,” Baldric thought to himself. “Eighty pounds and a little stubble would do her good.”

秃头喘着粗气。 他环顾四周,最后一次想着要回家,然后匆匆赶上笼子。 里面是一个年轻的精灵女人,身穿灰色囚服。 美丽,像瓷娃娃做成的肉。 然而,她拥有权威的气质,即使在黑暗中,鲍德瑞克也可以告诉她,她是一个有望服从的女人。 “实际上根本不是我的类型,” Baldric自言自语。 “ 80磅和一点点的茬将对她有好处。”

“Uhh, how do you know my name?” he whispered back.

“呃,你怎么知道我的名字?” 他小声回头。

“We don’t have time for explanations, but suffice it to say our meeting was preordained by powers greater than you or I. I take it you know who I am? Good. Now, there’s something I need you to do. Tonight.”

“我们没有时间进行解释,但是足以说我们的会议是由比您或我大的权力所预定的。我认为您知道我是谁吗? 好。 现在,我需要您做些事情。 今晚。”

“Me? Why, what could I possibly do? Why don’t you just break out and do it yourself?”

“我? 为什么,我可能怎么办? 您为什么不随便出去做自己呢?”

“Look at the ground Baldric, at the seal that blocks my Magic and holds me here more strongly than steel ever could.”

“看看地面的鲍德瑞克(Baldric),这是阻挡我的魔力并使我比钢更坚强的力量的海豹。”

Looking at the ground, Baldric could indeed see a circle around the cage composed of intricate patterns of faint-green numbers and letters. Studying the patterns, he felt a vague sense of understanding. He began to weave his own Logic, and…

看着地面,鲍德瑞克确实可以看到笼子周围有一个圆圈,上面有淡绿色数字和字母的复杂图案。 在研究模式时,他感到模糊的理解感。 他开始编织自己的逻辑,然后…

Cassandra’s eyes began to widen in surprise. “Stop that! What are you doing?”

卡桑德拉的眼睛开始惊讶地睁大。 “停下! 你在做什么?”

“Oh, you can see it too? I don’t know, it just almost seems like a puzzle, like I could…”

“哦,你也看到了吗? 我不知道,这几乎就像是一个谜,就像我能做到的那样……”

“No, you must leave it alone! It’s…it’s set to explode if anyone tries to undo it.” Composing herself, Cassandra’s mouth curved into a small smile.

“不,你必须别管它! 如果有人试图撤消它,它将爆炸。” 构成自己的卡桑德拉的嘴弯成一个小小的微笑。

“I must say, it’s extremely rare for anyone to be such a natural with Logic. But you must focus, and be very careful who you use Magic around. Other Magic users will spot you plain as day. In any case, listen closely. We are going to bring down the Emperor.”

“我必须说,对于Logic来说,如此自然的人是极为罕见的。 但是您必须专注,并且要非常小心周围使用Magic的人。 其他Magic用户会在一整天中发现您。 无论如何,请仔细听。 我们要打倒皇帝。”

Baldric felt like the wind had been knocked out of him.

鲍德瑞克觉得自己已经被风吹走了。

“Whoa whoa whoa, I’m just out for a walk lady. You can’t really mean…” Lowering his voice to the barest whisper, Baldric leaned towards Cassandra. “How would we do that?”

“哇,哇,我正要出去走走。 “你真的不是故意的……”将声音降到最卑鄙的耳语中,Baldric向Cassandra倾斜。 “我们将如何做?”

“First you must retrieve something for me. A lockbox, from the desk of the HR Manager.”

“首先,您必须为我找点东西。 来自人力资源经理办公桌的密码箱。”

Baldric gaped and spluttered trying to respond. “The the the, the the the…HR Manager? Look, I’m sorry lady, I really am, but what chance does a lazy old dwarf like me have against THAT thing? I’ve heard the rumors. I’m not doing it.”

Baldric茫然不语,试图回应。 “人力资源经理? 看,对不起,夫人,我确实是,但是像我这样的懒惰小矮人有什么机会反对那件事呢? 我听过谣言。 我没有这样做。”

“Tonight the creature will be absent from its lair.”

“今晚该生物将不在其巢穴中。”

“It’s lair? You mean HR’s facility, right?”

“是巢穴吗? 你是说人力资源的设施,对吗?

“No, the HR Manager has its own office underground, not too far from the facility. Like I said, it isn’t there right now, but for how long I cannot say, which is why you must go with all haste. Sneak into its office and retrieve from its desk a small black metal lockbox. Then return home and await my word.”

“不,人事经理在地下有自己的办公室,离工厂不远。 就像我说的,它现在不存在,但是我不能说多久,这就是为什么你必须全力以赴。 潜入办公室,从办公桌上取回一个黑色的小金属密码箱。 然后回家,等我的话。”

“Okay, let’s say I do all that. How exactly is that supposed to help us defeat the Emperor?”

“好的,可以说我做了所有这些。 那到底该如何帮助我们击败皇帝?”

Cassandra gave him a considering look. “I suppose you deserve to know what you’re getting into. The lockbox contains something we need for the fourth phase of my plans, which I’ll get to in a second. For phase two, after you acquire the lockbox, we shall sneak into the Emperor’s castle and destroy the source of his awesome powers. I know not what it is, only where it is located.”

卡桑德拉看了他一眼。 “我想你应该知道自己正在进入什么领域。 密码箱包含我们计划的第四阶段所需的内容,我将在第二部分中介绍。 对于第二阶段,在您获得密码箱之后,我们将潜入皇帝的城堡并摧毁其威力的来源。 我不知道它是什么,只有它的位置。”

Baldric wove Magic to record Cassandra’s plans.

鲍德瑞克(Baldric)编织魔术,以记录卡桑德拉(Cassandra)的计划。

# to store multiple objects, such as numbers or strings, try using a list
>>> objectives = ['steal lockbox', 'destroy power source']

>>> objectives
['steal lockbox', 'destroy power source']

>>> type(objectives)


This new type of object, the list, that Baldric had read about in the Book of Magic intrigued him, and he couldn’t help but think to himself, “If numbers could be converted to strings with str(), and certain strings could be converted to numbers with int() and float(), I wonder if lists can also be converted back and forth between different types too.”

鲍德瑞克(Baldric)在《魔法书》中读到的这种新对象,即清单,引起了他的兴趣,他忍不住想,“如果数字可以用str ()转换为字符串,并且某些字符串可以可以使用int ()和float ()转换为数字,我想知道列表是否也可以在不同类型之间来回转换。”

>>> list(4)
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: 'int' object is not iterable

>>> list(4.0)
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: 'float' object is not iterable

>>> list('steal lockbox')
['s', 't', 'e', 'a', 'l', ' ', 'l', 'o', 'c', 'k', 'b', 'o', 'x']

# aha, strings can be converted to lists!
# and integers and floats cannot be converted to lists

>>> int(objectives)
Traceback (most recent call last):
  File "python", line 1, in <module>
TypeError: int() argument must be a string, a bytes-like object or a number, not 'list'

>>> float(objectives)
Traceback (most recent call last):
  File "python", line 1, in 
TypeError: float() argument must be a string or a number, not 'list'

>>> str(objectives)
"['steal lockbox', 'destroy power source']"

# alternately, lists can be converted to strings
# but lists cannot be converted to integers or floats

Baldric realized Cassandra was speaking to him and tuned back in.

鲍德里克意识到卡桑德拉正在和他说话,然后调回去。

“Third, once the Emperor is weakened, we must free the prisoners from HR, many of whom are Magic users.”

“第三,皇帝被削弱后,我们必须将囚犯从人力资源中解放出来,其中许多人都是魔术师。”

“Well,” Baldric thought to himself, “if ‘+’ can combine strings, I’ll bet it can combine lists too.”

“好吧,”鲍德里克对自己说,“如果'+'可以合并字符串,我敢打赌它也可以合并列表。”

>>> objectives = objectives + ['free prisoners']
>>> objectives
['steal lockbox', 'destroy power source', 'free prisoners']

“I see, similar to strings indeed. I wonder if using the ‘*’ operator with a list and a number has a similar effect.”

“我知道,确实类似于弦乐。 我想知道将'*'运算符与列表和数字一起使用是否会产生类似的效果。”

>>> objectives * 2
['steal lockbox', 'destroy power source', 'free prisoners', 'steal lockbox', 'destroy power source', 'free prisoners']

“I think I’m starting to get the hang of this.”

“我想我开始对此一窍不通。”

“I can see your Magic you know, do try and concentrate!” Cassandra scolded. “Fourth, with the help of those Magic users, we hijack the Teleportation Circle and summon my rebel army to the heart of the Empire. We’ll need both your powers of Logic and a key that the lockbox contains in order to activate the Circle. Fifth, we assault the Emperor’s castle, and with our combined might, overthrow the Empire and slay the Emperor himself.”

“我可以看到你知道的魔术,尽力专心!” 卡桑德拉骂了。 “第四,在那些魔法使用者的帮助下,我们劫持了隐形运输圈子,并将我的叛军召唤到帝国的心脏。 我们需要您的逻辑能力和密码箱包含的钥匙才能激活Circle。 第五,我们进攻皇帝的城堡,并用我们的联合力量推翻了帝国,并杀死了皇帝本人。”

>>> objectives += ['hijack teleporter', 'assault castle'] # remember, x += y is the same as x = x + y
>>> objectives
['steal lockbox', 'destroy power source', 'free prisoners', 'hijack teleporter', 'assault castle']

Baldric, seeing how lists were similar to strings, thought to himself, “So if I wanted to get the first or last items in my list…”

Baldric看到列表与字符串的相似之处后,心想:“所以,如果我想获得列表中的第一项或最后一项……”

>>> objectives[0]
'steal lockbox'

>>> objectives[4] # also try >>> objectives[-1]
'assault castle'

“Just as expected. And again, just like strings, I’ll bet if I want a slice of the list, I just need to do something like…”

“正如预期的那样。 再说一次,就像字符串一样,我敢打赌,如果我想分一杯list,我只需要做类似的事情……”

# all items but the first
>>> objectives[1:]
['destroy power source', 'free prisoners', 'hijack teleporter', 'assault castle']

# third and fourth items
>>> objectives[2:4]
['free prisoners', 'hijack teleporter']

A question occurred to Baldric. Maybe Cassandra knew the answer. “Oh, I need to ask you, what’s with that purple web in the sky? It’s not your doing is it?”

Baldric遇到了一个问题。 也许卡桑德拉(Cassandra)知道答案。 “哦,我要问你,天空中的紫色网是什么? 不是你在做吗?”

“No Baldric, that is the creation of the HR Manager, a magical construct it weaves to capture and consume the dreams of the populace every night. If this is the first night you’ve seen it, it’s because your Magical powers have only recently emerged.”

“没有Baldric,这就是人力资源管理器的创建,它编织了一个神奇的结构,可以捕捉并消耗每晚的平民梦。 如果这是您第一次看到它,那是因为您的魔力才刚刚出现。”

“Come to think of it, I haven’t had any dreams in a long time…aside from one last night.”

“想一想,除了昨晚的一个梦,我很久没有做任何梦了。”

“Yes, Magical ability typically affords some protection from the HR Manager’s designs. But that won’t save you if it catches you in person.”

是的,神奇的能力通常可以为人力资源经理的设计提供一些保护。 但是,如果亲自抓住您,那将无法挽救您。”

Cassandra provided Baldric with details on how to infiltrate the HR Manager’s lair, then sent him on his way.

Cassandra向Baldric提供了有关如何渗透到人力资源经理的巢穴的详细信息,然后派他去了。

“Now that you understand what we’re up against, go with all haste, Baldric Hightower, and retrieve the lockbox from the desk of the HR Manager before it returns to its lair. There is a cart waiting for you just north of here which will take you to the underground entrance. Good luck, and may the Great Serpent watch over you.”

“现在,您已经了解了我们要面对的问题,与所有匆匆忙忙的Baldric Hightower一起去,并在人力资源管理器返回其巢穴之前从人力资源经理的办公桌中检索密码箱。 在这里北部,有一辆手推车等着您,将您带到地下入口。 祝你好运,大蛇守护你。”

With grim determination, Baldric nodded to Cassandra and set off on his way. Walking up the street, he soon found a donkey cart with its driver leaning against it, appearing to have dozed off. The driver didn’t look up as Baldric approached, but silently climbed into the front, leaving a seat open next to him. Baldric climbed on, and the driver set off.

博德瑞克下定决心,向卡桑德拉点了点头,然后出发了。 走在街上,他很快发现了一个驴车,司机靠着它,似乎昏昏欲睡。 鲍德瑞克(Baldric)走近时,驾驶员没有抬起头,而是默默地爬到了前排,在他旁边留了一个座位。 Baldric爬上去,司机出发了。

After a ride through the dark streets they pulled into an alley behind a warehouse. They were somewhere between the Emperor’s Palace and the HR facility now. The driver got off the cart and walked over to a nearby sewer access hatch.

在黑暗的街道上骑行之后,他们进入了仓库后面的一条小巷。 他们现在位于皇帝宫殿和人力资源设施之间。 司机下车,走到附近的下水道舱口。

“Here’s yer’ bloody manhole, sealed up tight with Magic. Wizards used to run this city you know, and they made sure not just anyone could go skulkin’ about the sewers. If you can get through there, you’ll climb down a ladder, turn right, follow the walk until you come to a dead end, then crawl through the grate and up the passage.”

“这是您血腥的人Kong,被魔术密封。 巫师曾经经营着这个你知道的城市,他们确保不仅没有人会嘲笑下水道。 如果可以到达那里,您将爬上梯子,向右转,沿着步道一直走到尽头,然后爬过炉the,然后爬上通道。”

Upon the sewer hatch was engraved:

下水道口上刻有:

Each line is a string That should be extended So multiply by 43 Oh that would be splendid

每行都是一个字符串,应该扩展,所以乘以43哦,这会很棒

Put the strings in a list Multiply it just the same Then use the string and list indices To solve this game

将字符串放入列表中乘以相同,然后使用字符串和列表索引来解决此游戏

Indices: [107][733], [137][898:902], [152][682:685], [187][864], [238][1301:1303], [253][957], [296][847:849], [334][-1], [-4][-2]

指数:[107] [733],[137] [898:902],[152] [682:685],[187] [864],[238] [1301:1303],[253] [957], [296] [847:849],[334] [-1],[-4] [-2]

“These pairs of indices given here are peculiar,” Baldric muttered to himself. “Ah, I think I see what’s going on here. Let’s say for example that I have a list containing a few strings, like the objectives list.”

“这里给出的这些对指数是奇特的,”鲍德里克自言自语。 “啊,我想我知道这是怎么回事。 例如,假设我有一个包含一些字符串的列表,例如目标列表。”

>>> objectives = ['steal lockbox', 'destroy power source', 'free prisoners', 'hijack teleporter', 'assault castle']

“Then if I apply a pair of indices to that list, such as [2][5], I’ll be selecting the list element at index 2, then the character at index 5 of that list element.”

“然后,如果我将一对索引应用于该列表,例如[2] [5],我将选择索引2处的列表元素,然后选择该列表元素的索引5处的字符。”

>>> objectives[2]
'free prisoners'

>>> objectives[2][5]
'p'

“And I bet I can get string slices like this too.”

“而且我敢打赌我也可以得到这样的字符串切片。”

>>> objectives[2][5:9]
'pris'

“Just as I thought. Alright then, let’s get this manhole open.”

“正如我所预料的那样。 好吧,让我们打开这个沙井。”

s1 = 'Each line is a string'
s2 = 'That should be extended'
s3 = 'So multiply by 43'
s4 = 'Oh that would be splendid'
s5 = 'Put the strings in a list'
s6 = 'Multiply it just the same'
s7 = 'Then use the string and list indices'
s8 = 'To solve this game'
n = 43

string_list = [s1*n, s2*n, s3*n, s4*n, s5*n, s6*n, s7*n, s8*n]

final_list = string_list * n

# use back slashes to continue one line onto multiple lines for readability
answer = final_list[107][733] + final_list[137][898:902] + final_list[152][682:685] + 
         final_list[187][864] + final_list[238][1301:1303] + final_list[253][957] + 
         final_list[296][847:849] + final_list[334][-1] + final_list[-4][-2]

print(answer)
what is busyness

“What is busyness? Hmm. Busyness is…no, not progress. It’s a disease, if you ask me. It’s death.”

“什么是忙? 嗯 忙是……不,不是进步。 如果你问我,这是一种疾病。 这是死亡。”

With that, the text on the sewer hatch vanished, and the circular cover swung upward, revealing the top of a ladder leading down into darkness. Baldric climbed down, and the lid shut behind him. The driver climbed back on his cart.

这样一来,下水道舱口上的文字消失了,圆形盖子向上摆动,露出了通向黑暗的梯子顶部。 鲍德瑞克爬下,盖子在他身后关上。 司机爬回他的手推车。

“What a dwarf is doing crawling through manholes at this hour I don’t want to know. Manhole. Hehe, what a word.”

“我不知道这个小时矮人正在通过人Kong爬行。 沙井。 呵呵,一个字。

The driver and his donkey slowly made their way through the night, the Magical web still silently lurking over the city. High above it the moon rose in the sky, and was momentarily obscured by a large winged silhouette.

驾驶员和他的驴子整夜缓慢驶入,Magical网仍然默默地潜伏在这座城市上空。 高高的月亮在天空中升起,瞬间被一个巨大的有翼剪影所遮盖。



Congratulations, you earned 97 experience and 24 gold! You are now a Level 2 Dwarven Apprentice! (cue victory music)

恭喜,您获得了97点经验和24金! 您现在是2级矮人学徒! (提示胜利的音乐

Here are the Python topics you covered (and may want to DuckDuckGo for further inquiry):

这是您涵盖的Python主题(并且可能需要DuckDuckGo进行进一步的查询):

  • strings
  • lists
  • string and list concatenation
  • extending strings and lists via multiplication
  • string and list indexing
  • string and list slicing
  • converting data types with int(), float(), str(), and list()
  • multi-line comments/strings (using triple quotes)
  • 清单
  • 字符串和列表串联
  • 通过乘法扩展字符串和列表
  • 字符串和列表索引
  • 字符串和列表切片
  • 使用int (), float (), str ()和list ()转换数据类型
  • 多行注释/字符串(使用三引号)


翻译自: https://www.pybloggers.com/2017/11/intro-to-python-chapter-2-strings-and-lists/

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值