在python中,有一个称为string的标准库。在字符串模块中,存在与字符串相关的不同常量,方法和类。
要使用这些模块,我们需要在代码中导入字符串模块。
import string
一些字符串常量及其对应的值如下所示:
| 序号 | 将字符串常量和值放入其中 |
|---|---|
| 1 | string.ascii_lowercase'abcdefghijklmnopqrstuvwxyz ' |
| 2 | string.ascii_uppercase'ABCDEFGHIJKLMNOPQRSTUVWXYZ ' |
| 3 | string.ascii_letters asci_lowwecase和ascii_uppercase'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'的串联 |
| 4 | string.digits'0123456789 ' |
| 5 | string.hexdigits'0123456789abcdefABCDEF ' |
| 6 | string.octdigits'01234567 ' |
| 7 | string.punctuation '!“#$%&\'()* +,-。/ :; <=>?@ [\\] ^ _`{|}〜' |
| 8 | string.printable 所有可打印的ASCII字符。它是asci_letters,标点符号,数字和空格的集合。'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!“#$%&\'()* +,-。/ :; <=>?@ [\\] ^ _`{|}〜\ t \ n \ r \ x0b \ x0c' |
| 9 | string.whitespace '\ t \ n \ r \ x0b \ x0c' |
import string print(string.hexdigits) print(string.ascii_uppercase) print(string.printable)
输出结果
0123456789abcdefABCDEF
ABCDEFGHIJKLMNOPQRSTUVWXYZ
0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&'()*+,-./:;<=>?@[\]^_`{|}~python中的内置字符串类通过该format()方法支持不同的复杂变量替换和值格式。
要格式化字符串,基本语法是-
‘{} {}’.format(a, b)a和b的值将放置在用“ {}”括起来的那些位置。我们还可以在花括号内提供位置参数。或者在括号内写一些变量名也是有效的。
使用此格式选项,我们还可以将填充设置为文本。要在文本中添加填充,语法如下:
‘{: (character) > (width)}’.format(‘string’)“字符串”将使用特定字符填充,宽度使用[>符号在右侧,宽度值。我们可以使用<填充到左侧。^设置在中间。
该format()方法还可以使用给定的长度截断字符串。语法就像-
‘{:.length}’.format(‘string’)字符串将被截短至给定的长度。
print('The Name is {} and Roll {}'.format('Jhon', 40))
print('The values are {2}, {1}, {3}, {0}'.format(50, 70, 30, 15)) #Using positional parameter
print('Value 1: {val1}, value 2: {val2}'.format(val2 = 20, val1=10)) #using variable name
#Padding the strings
print('{: >{width}}'.format('Hello', width=20))
print('{:_^{width}}'.format('Hello', width=20)) #Place at the center. and pad with '_' character
#Truncate the string using given length
print('{:.5}'.format('Python Programming')) #Take only first 5 characters输出结果
The Name is Jhon and Roll 40 The values are 30, 70, 15, 50 Value 1: 10, value 2: 20 Hello _______Hello________ Pytho
模板字符串用于用更简单的方法替换字符串。该模板支持使用$字符进行替换。当$标识被发现,它会与标识符的新值替换
要将模板用于字符串,基本语法为-
myStr = string.Template(“$a will be replaced”) myStr.substitute(a = ‘XYZ’)
字符串中a的值将替换为字符串中的“ XYZ”。我们可以使用字典来执行这种操作。
my_template = string.Template("The value of A is $X and Value of B is $Y")
my_str = my_template.substitute(X = 'Python', Y='Programming')
print(my_str)
my_dict = {'key1' : 144, 'key2' : 169}
my_template2 = string.Template("The first one $key1 and second one $key2")
my_str2 = my_template2.substitute(my_dict)
print(my_str2)输出结果
The value of A is Python and Value of B is Programming The first one 144 and second one 169