将字符串转换为其ascii值的整数 [英] Convert a string into an integer of its ascii values
问题描述
我正在尝试编写一个接受字符串txt
并返回该字符串的字符的ascii数字的int的函数.它还需要第二个参数n
,它是一个整数,它指定每个字符应转换为的位数. n的默认值为3.n始终> 3,并且字符串输入始终为非空.
I am trying to write a function that takes a string txt
and returns an int of that string's character's ascii numbers. It also takes a second argument, n
, that is an int that specified the number of digits that each character should translate to. The default value of n is 3. n is always > 3 and the string input is always non-empty.
示例输出:
string_to_number('fff')
102102102
string_to_number('ABBA', n = 4)
65006600660065
我当前的策略是通过将txt
转换为列表来将其拆分为字符.然后,我将字符转换为它们的ord
值,并将其附加到新列表中.然后,我尝试将这个新列表中的元素组合成一个数字(例如,我将从['102', '102', '102']
转到['102102102']
.然后,我尝试将该列表的第一个元素(也称为唯一元素)转换为整数.我当前的代码如下:
My current strategy is to split txt
into its characters by converting it into a list. Then, I convert the characters into their ord
values and append this to a new list. I then try to combine the elements in this new list into a number (e.g. I would go from ['102', '102', '102']
to ['102102102']
. Then I try to convert the first element of this list (aka the only element), into an integer. My current code looks like this:
def string_to_number(txt, n=3):
characters = list(txt)
ord_values = []
for character in characters:
ord_values.append(ord(character))
joined_ord_values = ''.join(ord_values)
final_number = int(joined_ord_values[0])
return final_number
问题是我得到了Type Error
.我可以编写成功返回单字符字符串整数的代码,但是对于包含多个字符的字符,由于这种类型错误,我不能这样做.有什么办法解决这个问题.谢谢,如果很长的话,我们深表歉意.
The issue is that I get a Type Error
. I can write code that successfully returns the integer of a single-character string, however when it comes to ones that contain more than one character, I can't because of this type error. Is there any way of fixing this. Thank you, and apologies if this is quite long.
推荐答案
尝试一下:
def string_to_number(text, n=3):
return int(''.join('{:0>{}}'.format(ord(c), n) for c in text))
print(string_to_number('fff'))
print(string_to_number('ABBA', n=4))
输出:
102102102
65006600660065
编辑:不带列表理解,如OP在评论中要求的那样
without list comprehension, as OP asked in the comment
def string_to_number(text, n=3):
l = []
for c in text:
l.append('{:0>{}}'.format(ord(c), n))
return int(''.join(l))
有用的链接:
Useful link(s):
- Python中的字符串格式:包含您需要了解的几乎所有内容python中的字符串格式
- string formatting in python: contains pretty much everything you need to know about string formatting in python
这篇关于将字符串转换为其ascii值的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!