在python中将字符串/字符转换为整数

发布于 2024-08-15 09:22:17 字数 58 浏览 1 评论 0原文

我想将字符串的单个字符转换为整数,加2,然后将其转换回字符串。因此,A 变为 C,K 变为 M,等等。

I want to convert a single character of a string into an integer, add 2 to it, and then convert it back to a string. Hence, A becomes C, K becomes M, etc.

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(8

爱殇璃 2024-08-22 09:22:17

这是通过 chr 和 ord 函数完成的。例如; chr(ord(ch)+2) 执行您想要的操作。 此处对此进行了完整描述。

This is done through the chr and ord functions. Eg; chr(ord(ch)+2) does what you want. These are fully described here.

北陌 2024-08-22 09:22:17

这听起来很像家庭作业,所以我会给你几块,然后让你填写其余的。

要访问字符串 s 的单个字符,可以使用 s[x],其中 x 是整数索引。索引从 0 开始。

要获取字符的整数值,可以使用 ord(c),其中 c 是字符。要将整数转换回字符,请使用 chr(x)。小心靠近字母表末尾的字母!

编辑:如果您无法想出如何处理 Y 和 Z,请发表评论,我会给出提示。

This sounds a lot like homework, so I'll give you a couple of pieces and let you fill in the rest.

To access a single character of string s, its s[x] where x is an integer index. Indices start at 0.

To get the integer value of a character it is ord(c) where c is the character. To cast an integer back to a character it is chr(x). Be careful of letters close to the end of the alphabet!

Edit: if you have trouble coming up with what to do for Y and Z, leave a comment and I'll give a hint.

沉溺在你眼里的海 2024-08-22 09:22:17

通常情况下,只需对 2 和 chr 进行排序和添加即可,(Y, Z 会给你意想不到的结果 ("[","\")

>>> chr(ord("A")+2)
'C'

如果你想将 Y, Z 更改为 A, B,你可以这样做。

>>> chr((ord("A")-0x41+2)%26+0x41)
'C'
>>> chr((ord("Y")-0x41+2)%26+0x41)
'A'
>>> chr((ord("Z")-0x41+2)%26+0x41)
'B'

这里是从头到尾

>>> [chr((i-0x41+2)%26+0x41) for i in range(0x41,0x41+26)]
['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A', 'B']

Normally, Just ord and add 2 and chr back, (Y, Z will give you unexpected result ("[","\")

>>> chr(ord("A")+2)
'C'

If you want to change Y, Z to A, B, you could do like this.

>>> chr((ord("A")-0x41+2)%26+0x41)
'C'
>>> chr((ord("Y")-0x41+2)%26+0x41)
'A'
>>> chr((ord("Z")-0x41+2)%26+0x41)
'B'

Here is A to Z

>>> [chr((i-0x41+2)%26+0x41) for i in range(0x41,0x41+26)]
['C', 'D', 'E', 'F', 'G', 'H', 'I', 'J', 'K', 'L', 'M', 'N', 'O', 'P', 'Q', 'R', 'S', 'T', 'U', 'V', 'W', 'X', 'Y', 'Z', 'A', 'B']
只是我以为 2024-08-22 09:22:17

http://docs.python.org/library/functions.html

ord(c )

给定长度为 1 的字符串,当参数是 unicode 对象时,返回表示字符的 Unicode 代码点的整数;当参数是 8 位字符串时,返回表示字节值的整数。例如,ord('a') 返回整数 97,ord(u'\u2020') 返回 8224。这与 8 位字符串的 chr() 和 unicode 对象的 unichr() 相反。如果给出了 unicode 参数并且 Python 是使用 UCS2 Unicode 构建的,则字符的代码点必须在 [0..65535] 范围内(包括 [0..65535]);否则字符串长度为 2,并且将引发 TypeError。

http://docs.python.org/library/functions.html

ord(c)

Given a string of length one, return an integer representing the Unicode code point of the character when the argument is a unicode object, or the value of the byte when the argument is an 8-bit string. For example, ord('a') returns the integer 97, ord(u'\u2020') returns 8224. This is the inverse of chr() for 8-bit strings and of unichr() for unicode objects. If a unicode argument is given and Python was built with UCS2 Unicode, then the character’s code point must be in the range [0..65535] inclusive; otherwise the string length is two, and a TypeError will be raised.

泪痕残 2024-08-22 09:22:17

“ord”只是解决方案的一部分。你提到的拼图会旋转,因此“X”+3旋转为“A”。其中最著名的是 rot-13,它轮换 13 个角色。应用 rot-13 两次(旋转 26 个字符)会使文本恢复原状。

处理这个问题最简单的方法是使用转换表。

import string

def rotate(letters, n):
    return letters[n:] + letters[:n]

from_letters = string.ascii_lowercase + string.ascii_uppercase
to_letters = rotate(string.ascii_lowercase, 2) + rotate(string.ascii_uppercase, 2)

translation_table = string.maketrans(from_letters, to_letters)

message = "g fmnc wms bgblr"
print message.translate(translation_table)

这里没有一个 ord() 或 chr() 。那是因为我回答的问题与所问的问题不同。 ;)

"ord" is only part of the solution. The puzzle you mentioned there rotates, so that "X"+3 rotates to "A". The most famous of these is rot-13, which rotates 13 characters. Applying rot-13 twice (rotating 26 characters) brings the text back to itself.

The easiest way to handle this is with a translation table.

import string

def rotate(letters, n):
    return letters[n:] + letters[:n]

from_letters = string.ascii_lowercase + string.ascii_uppercase
to_letters = rotate(string.ascii_lowercase, 2) + rotate(string.ascii_uppercase, 2)

translation_table = string.maketrans(from_letters, to_letters)

message = "g fmnc wms bgblr"
print message.translate(translation_table)

Not a single ord() or chr() in here. That's because I'm answering a different question than what was asked. ;)

成熟稳重的好男人 2024-08-22 09:22:17

尝试 ord(),应该可以解决问题:)

Try ord(), should do the trick :)

沐歌 2024-08-22 09:22:17

对于整个字符串,这将是:

>>> s = "Anne"
>>> ''.join([chr(ord(i)+2) for i in s]) 
'Cppg'

It's diffucult for 'Y', 'Z' ...

>>> s = "Zappa"
>>> ''.join([chr(ord(i)+2) for i in s]) 
'\\crrc'

Functions: chrord

For a whole string this would be:

>>> s = "Anne"
>>> ''.join([chr(ord(i)+2) for i in s]) 
'Cppg'

It's diffucult for 'Y', 'Z' ...

>>> s = "Zappa"
>>> ''.join([chr(ord(i)+2) for i in s]) 
'\\crrc'

Functions: chr, ord

野稚 2024-08-22 09:22:17

对于那些需要对字符串的每个字符执行操作的人,处理此问题的另一种方法是将 str 对象转换为 bytes 对象,这将利用事实上,bytes 对象只是一个整数序列。

import numpy


old_text_str = "abcde"  # Original text
old_num_list = list(old_text_str.encode())  # Integer values of the original text
new_num_list = numpy.add(old_num_list, 2).tolist()  # Add +2 to the integer values
new_text_str = bytes(new_num_list).decode()  # Updated text

print(f"{old_text_str=}")
print(f"{old_num_list=}")
print(f"{new_num_list=}")
print(f"{new_text_str=}")

输出:

old_text_str='abcde'
old_num_list=[97, 98, 99, 100, 101]
new_num_list=[99, 100, 101, 102, 103]
new_text_str='cdefg'

相关主题:

For those who need to perform the operation on each character of the string, another way of handling this is by converting the str object to/from a bytes object which will take advantage of the fact that a bytes object is just a sequence of integers.

import numpy


old_text_str = "abcde"  # Original text
old_num_list = list(old_text_str.encode())  # Integer values of the original text
new_num_list = numpy.add(old_num_list, 2).tolist()  # Add +2 to the integer values
new_text_str = bytes(new_num_list).decode()  # Updated text

print(f"{old_text_str=}")
print(f"{old_num_list=}")
print(f"{new_num_list=}")
print(f"{new_text_str=}")

Output:

old_text_str='abcde'
old_num_list=[97, 98, 99, 100, 101]
new_num_list=[99, 100, 101, 102, 103]
new_text_str='cdefg'

Related topics:

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文