python a=b=c函数等
有没有像change_字母顺序($string,$number)这样的函数可以将$string,$number中的每个字母向前更改几次 范例python a=b=c函数等,python,function,alphabetical,Python,Function,Alphabetical,有没有像change_字母顺序($string,$number)这样的函数可以将$string,$number中的每个字母向前更改几次 范例 print change_alphabetical("abc",2) 印刷品: "cde" zab 或 印刷品: "cde" zab 我不知道有哪款内置软件能做到这一点,但您可以自己开发: def change(string, position): alphabet = "abcdefghijklmnopqrstuvwxyz" i
print change_alphabetical("abc",2)
印刷品:
"cde"
zab
或
印刷品:
"cde"
zab
我不知道有哪款内置软件能做到这一点,但您可以自己开发:
def change(string, position):
alphabet = "abcdefghijklmnopqrstuvwxyz"
indexes = [alphabet.find(char) for char in string]
new_indexes = [(i + position) % 26 for i in indexes]
output = ''.join([alphabet[i] for i in new_indexes])
return output
print change("abc", -1) # zab
它本质上接受输入字符串中的每个字符,并使用some\u list.find()
方法将其转换为数字位置。然后,它添加偏移量mod 26,以获得新索引以及随后的新字符串
请记住,这仅适用于小写字母(尽管您始终可以使用string=string.lower()
),如果您希望使用除英文字母以外的其他字母,则需要进行调整
如果您确实希望代码在国际上运行,您可以使用
locale
模块获取给定某种任意语言的本地字母表:
import locale
locale.setlocale(locale.LC_ALL, '')
import string
def change(string, position):
alphabet = string.lowercase
indexes = [alphabet.find(char) for char in string.lower()]
new_indexes = [(i + position) % len(alphabet) for i in indexes]
output = ''.join([alphabet[i] for i in new_indexes])
return output
目前,这只是获取当前计算机设置为的任何本地的字母表。我相信您可以通过编辑locale.setlocale
中的第二个参数来更改基础语言
然后,string.lowercase
属性将按顺序返回给定语言的所有小写字母
请记住,
locale.setlocale
不被认为是线程安全的,它将应用于整个程序 change\u alpabetical('ab12cd',1)
和change\u alpabetical('Ordóñez',1)
的预期结果是什么?
import string
def change(word, pos):
old = string.ascii_lowercase
new = old[pos:] + old[:pos]
return word.translate(string.maketrans(old, new))