Python基础四【字符串】

 1 #双引号:使用双引号的一个好处,就是字符串中可以使用单引号字符。
 2 #“转义字符”让你输入一些字符,它们用其他方式是不可能放在字符串里的。转义字符包含一个倒斜杠(\),单引号的转义字符是\’。
 3 #\" 双引号
 4 #\t 制表符
 5 #\n 换行符
 6 #\\ 倒斜杠
 7 #原始字符串:在字符串开始的引号之前加上 r,
 8 spam = 'Say hi to Bob\'s mother.'
 9 print(spam)
10 #多行字符串
11 print('''Dear Alice,
12 Eve's cat has been arrested for catnapping, cat burglary, and extortion.
13 Sincerely,
14 Bob''')
15 #字符串下标和切片
16 #字符串的 in 和 not in 操作符
17 #字符串方法 upper()、lower()、isupper()和 islower(),返回新字符串,原字符串不变
18 
19 #只有字母:isalpha()
20 #串只包含字母和数字,并且非空,isalnum()
21 #只包含数字字符,并且非空,isdecimal()
22 #只包含空格、制表符和换行,并且非空,isspace()
23 #仅包含以大写字母开头、后面都是小写字母的单词, istitle()
24 #字符串方法 startswith()和 endswith():如果它们所调用的字符串以该方法传入的字符串开始或结束,返回 true。否则,方法返回 False。
25 
26 #字符串方法 join()和 split()
27 print(', '.join(['cats', 'rats', 'bats'])) #cats, rats, bats
28 ' '.join(['My', 'name', 'is', 'Simon'])
29 'ABC'.join(['My', 'name', 'is', 'Simon'])
30 
31 'My name is Simon'.split()#默认情况下,字符串'My name is Simon'按照各种空白字符分割,诸如空格、制表符或换行符。
32 
33 # spam.split('\n')# 按换行符分隔
34 #用 rjust()、ljust()和 center()方法对齐文本
35 print('Hello'.rjust(10))#     Hello,是说我们希望右对齐,将'Hello'放在一个长度为 10 的字符串中
36 
37 print('Hello'.rjust(10,'*'))#*****Hello, 可设置填充字符
38 
39 'Hello'.center(20)
40 
41 print('  Hello  '.center(50, '='))#====================  Hello  =====================
42 
43 def printPicnic(itemsDict, leftWidth, rightWidth):
44     print('PICNIC ITEMS'.center(leftWidth + rightWidth, '-'))
45     for k, v in itemsDict.items():
46         print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))
47 picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
48 printPicnic(picnicItems, 12, 5)
49 printPicnic(picnicItems, 20, 6)
50 
51 #文本每行前面加个*
52 text="Lists of animals\nLists of aquarium life\nLists of biologists by author abbreviation\nLists of cultivars"
53 lines = text.split('\n')
54 for i in range(len(lines)): # loop through all indexes in the "lines" list
55     lines[i] = '* ' + lines[i]  # 连接修改过的行
56 # print(lines)
57 text = '\n'.join(lines)
58 print(text)

 

posted @ 2022-10-13 16:00  山顶听风  阅读(34)  评论(0)    收藏  举报