maketrans python3 string () and translate () using

    When you want to replace some of the letters of a string might use replace () method, but it was used many times, too much trouble, in fact, python also provides a more convenient function, which is makestrans () and translate (), which requires two functions can be achieved only with the use of the above requirements.

    At the beginning of learning English through English in our school has five vowels, aeiou. Here we give an example, it is to replace the vowels in a word of English to 12345, if you can, then get rid of punctuation.

import string
mystr = "this is string example....wow!!!"
intab = "aeiou"
outtab = "12345"
deltab = ".!"

As described above: Example string is "", which comprises a plurality of word vowels, we have to replace 12345. i.e. aeiou respectively:

a-->1;

e-->2;

i-->3;

o-->4;

u-->5

And preferably wherein the punctuation "...!" Removed, three methods are given here, only the punctuation removed only then in a third method

# maketrans()方法接受的是一个参数,这个参数得是字典
mydict = dict(zip(intab, outtab))
trantab1 = str.maketrans(mydict) 
print("trantab1:", trantab1)

# maketrans()方法接受的是两个参数,这两个参数需要是长度相同的字符串
trantab2 = str.maketrans(intab, outtab) 
print("trantab2:", trantab2)

# maketrans()方法接受的是三个参数,前两个参数需要是长度相同的字符串,第三个字符串是会删除的字符
trantab3 = str.maketrans(intab, outtab, deltab) 
print("trantab3:", trantab3)

# translate()方法在python3中只能接受一个参数,这与py2中不同
print(mystr.translate(trantab1))
print(mystr.translate(trantab2))
print(mystr.translate(trantab3))

The output of the above code as follows:

trantab1: {97: '1', 101: '2', 105: '3', 111: '4', 117: '5'}
trantab2: {97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
trantab3: {97: 49, 101: 50, 105: 51, 111: 52, 117: 53, 46: None, 33: None}
th3s 3s str3ng 2x1mpl2....w4w!!!
th3s 3s str3ng 2x1mpl2....w4w!!!
th3s 3s str3ng 2x1mpl2w4w

Corresponding to the key value can be seen ultimately generate the dictionary, you need to delete the character is None

Guess you like

Origin blog.csdn.net/a857553315/article/details/90416783