如何在 Python 中显示字符串的前几个字符? [英] How to display the first few characters of a string in Python?

查看:180
本文介绍了如何在 Python 中显示字符串的前几个字符?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我刚开始学习 Python,但我现在有点卡住了.

Hi I just started learning Python but I'm sort of stuck right now.

我有 hash.txt 文件,其中包含数以千计的 MD5、Sha1 和 Sha5 中的恶意软件哈希,每行中分别用分隔符分隔.下面是我从 .txt 文件中提取的 2 行示例.

I have hash.txt file containing thousands of malware hashes in MD5, Sha1 and Sha5 respectively separated by delimiters in each line. Below are 2 examples lines I extracted from the .txt file.

416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07b9f7d7f7f7d7f7f9f7d2c8c8f9f7d356a99a4205a4d6cab2dcae414a5670fd|612aeeeaa8aa432a7b96202847169ecae56b07ee|d17de7ca4c8f24ff49314f0f342dbe9296f6e>ccb528e6f16d1b28e6d1b3eb28e6d1b3e

416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f 56a99a4205a4d6cab2dcae414a5670fd|612aeeeaa8aa432a7b96202847169ecae56b07ee|d17de7ca4c8f24ff49314f0f342dbe9243b10e9f3558c6193e2fd6bccb1be6d2

我的目的是显示前 32 个字符(MD5 哈希),因此输出将如下所示:

My intention is to display the first 32 characters (MD5 hash) so the output will look something like this:

416d76b8811b0ddae2fdad8f4721ddbe 56a99a4205a4d6cab2dcae414a5670fd

416d76b8811b0ddae2fdad8f4721ddbe 56a99a4205a4d6cab2dcae414a5670fd

有什么想法吗?

推荐答案

您可以非常轻松地对 string 进行切片",就像从 list:

You can 'slice' a string very easily, just like you'd pull items from a list:

a_string = 'This is a string'

获取前 4 个字母:

first_four_letters = a_string[:4]
>>> 'This'

或最后 5 个:

last_five_letters = a_string[-5:]
>>> 'string'

因此将该逻辑应用于您的问题:

So applying that logic to your problem:

the_string = '416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f '
first_32_chars = the_string[:32]
>>> 416d76b8811b0ddae2fdad8f4721ddbe

这篇关于如何在 Python 中显示字符串的前几个字符?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆