5. 字符串

基于网络课程《Python全栈开发专题》 记录笔记,请支持正版课程

字符串格式化

%的使用

# %s 代表字符串的占位符
formatStr = 'Are you %s? I\'m %s.'
values = ('OK', 'XiaoMing')
print(formatStr % values)

# %f 浮点数
# %d 整数
from math import pi;
# formatStr = 'PI是圆周率,PI的值是:%f'
formatStr = 'PI是圆周率,PI的值是:%.2f (保留小数点后%d位)'
values = (pi, 2)
print(formatStr % values)

# %转义: %%
formatStr = '降水概率%d%%'
values = (57)
print(formatStr % values)

用Template类格式化字符串

from string import Template
template1 = Template('$lang是一种编程语言,$lang很容易学习,给你打$score分。')
# 用命令参数传入
print(template1.substitute(lang='Python', score=100))

# 可以使用${}
template2 = Template('${s}stitute')
print(template2.substitute(s='sub'))

# 转义:$$
template3 = Template('$dollar$$相当于多少$pounds英镑')
print(template3.substitute(dollar=20, pounds=25))

# 也可以传入字典
template4 = Template('姓别$sex,爱好$like')
data = {}
data['sex'] = '男'
data['like'] = '女'
print(data)
print(template4.substitute(data))

使用format格式化字符串

# 匿名,按顺序传参
s1 = '今天是 {}, 温度{}。'
print(s1.format('星期三', '24摄氏度'))

# 使用命名参数传参
s2 = '今天是 {week}, 温度{x}。'
print(s2.format(week = '星期三', x = '26度'))

# 匿名和命名的混用
s3 = '一{}, 二{two}, 三{three}, 四{}'
# 把所有匿名的放在前面,命名的随便写
print(s3.format(1, 4, two=2, three=3))

# 使用序号格式化参数
s4 = '一{1}, 二{two}, 三{0}, 四{four}'
print(s4.format(3, 1, two=2, four=4))

# 获取列表中的指定值
nums = [1, 2, 3, 4]
s5 = '一{nums[0]}, 二{nums[1]}, 三{nums[2]}, 四{nums[3]}'
print(s5.format(nums=nums))

# 使用属性
import math
s6 = 'The {mod.__name__} module defines the vlaue for {mod.pi}'
print(s6.format(mod=math))

format字符串格式化类型符

  • a 将字符串按unicode编码输出
  • b 将一个整数格式化为一个二进制数
  • c ASCII
  • d 十进制
  • e/E 科学计数法
  • f/F 浮点数
  • g/G 会根据整数时的位数在浮点数和科学计数法之间切换,在整数位超过6位时与E相同,否则与F相同
  • o 八进制
  • s 按原样格式化字符串
  • x/X 十六进制(大小写字母)
  • % 百分比
s1 = '原样输出: {first!s}; 调用repr函数: {first!r} 输出Unicode:{first!a}'
print(s1.format(first="中"))

# 将一个整数按浮点数格式输出
s2 = '整数:{num}; 浮点数: {num:f}'
print(s2.format(num=5))

# 进制转换
s3 = '十进制:{num}; 二进制:{num:b}; 八进制:{num:o}; 十六进制:{num:x}'
print(s3.format(num=128))

# 科学计数法
s4 = '科学计数法:{num:e}'
print(s4.format(num = 678980000000000000))

# 浮点数按百分比输出
s5 = '百分比:{num:%}'
print(s5.format(num=0.3478))  # 34.780000%

s5 = '百分比:{num:.1%}'
print(s5.format(num=0.3478))  # 34.8%

format 字段宽度、精度、千位分隔符

# 固定宽度
print("a:{num:12}".format(num = 32))
print("a:{num:<12}".format(num = 32))
print("a:{num:^12}".format(num = 32))

# create table
print("{header1:8}{header2:5}".format(header1='姓名', header2='年龄'))
print("{cell11:8}{cell12:5}".format(cell11='张三', cell12=18))
print("{cell21:8}{cell22:5}".format(cell21='李四', cell22=23))
print("{cell31:8}{cell32:5}".format(cell31='二狗', cell32=27))

# 精度
from math import pi
import math
print('float number: {pi:.2f}'.format(pi=pi))
print('float number: {obj.pi:.2f}'.format(obj=math))
print('float number: {pi: 20.4f}'.format(pi = pi))

# 截取字符串
print('{msg:.5}'.format(msg='hello world'))   # 截取前5个字符

# 千位分隔符
print('GooGol is {:,}: '.format(10 ** 100))

对齐和填充

from math import pi
print('{pi:012.3f}'.format(pi = pi))    # 00000003.142
print('{pi:0>12.3f}'.format(pi = pi))   # 00000003.142

# < 左对齐  ^ 居中  > 右对齐 
print('{pi:#>12.3f}'.format(pi = pi))   # #######3.142
print('{pi:#>12.3f}'.format(pi = -pi))   # ######-3.142
print('{pi:0=12.3f}'.format(pi = -pi))   # -0000003.142

center方法

# <      hello      >
print('<' + 'hello'.center(30) + '>') # <            hello             >

print('<{:^30}>'.format("hello"))     # 同上

# 填充左右
print('<' + 'hello'.center(20, '*') + '>')  # <*******hello********>
print('<{:*^20}>'.format("hello"))          # 同上

find方法

s = 'hello world'
print(s.find('world'))   # 6
# find一个不存在的
print(s.find('x'))  # -1
# 出现多次的,返回第一次出现的位置
print(s.find('o'))  # 4
# 从第六个位置开始找
print(s.find('o', 6))  # 7
# 指定起始位置,左闭右开
print(s.find('l', 5, 9))

join方法

myList = ['a', 'b', 'c', 'd', 'e']
s = '*'

print(s.join(myList))   # a*b*c*d*e
print(' | '.join(myList))  # aAAAbAAAcAAAdAAAe

# 生成win/Unix系统路径
# C:/usr/local/nginx
# /usr/local/nginx
dirs = '', 'usr', 'local', 'nginx'
linuxPath = '/'.join(dirs)
winPath = 'C:' + '\\'.join(dirs)

print(linuxPath)
print(winPath)

# 
numList = [1, 2, 3, 4, 5]
# 抛出异常
# print('a'.join(numList))
'''
Traceback (most recent call last):
  File "H:\PythonWorkSpace\first-python\src\First.py", line 19, in <module>
print('a'.join(numList))
TypeError: sequence item 0: expected str instance, int found
'''

split方法

s1 = 'a b c d e f'
print(s1.split())   # ['a', 'b', 'c', 'd', 'e', 'f']

s2 = 'a**b**c**d**e**f'
print(s2.split('**'))  # ['a', 'b', 'c', 'd', 'e', 'f']

path = '/usr/local/nginx'
pathList = path.split('/')
print(pathList)  # ['', 'usr', 'local', 'nginx']
winPath = 'D:' + '\\'.join(pathList)
print(winPath)   # D:\usr\local\nginx

upper, lower和capwords

print('Apple'.lower())
print('Apple'.upper())

myList = ['Python', 'Ruby', 'Java', 'Kotlin']
if 'KOTLIN' in myList:
    print('找到Kitlin!')
else:
    print('未找到Kotlin')
    
for lang in myList:
    if 'kotlin' == lang.lower():
        print("OK")
        break
    
from string import capwords

s = 'i not only like python, but alse like kotlin.'
print(capwords(s))   # I Not Only Like Python, But Alse Like Kotlin.

replace和strip

s = 'abcdaaefg'
print(s.replace('a', '12345'))  # 12345bcd1234512345efg
print(s.replace('xxxxxxx', '12345'))  # 没有就不替换

# strip (trim)
print('  asdfasdf asdfasf    '.strip())

# 可以输入多种字符,几个字符之间是“或”的关系
s = '*** $$* Hello * World   ***$$$'
print(s.strip(' *$'))   # Hello * World

translate 和 maketrans

"".translate()替换单个字符串

# translate 替换单个字符
s = "I'm not only like Python, but also like Kotlin."

# 把“a”替换成"*",把“k”替换成“$”
table = s.maketrans('ak', '*$')   # {97: 42, 107: 36}  ASCII : 97-a ; 42-* ; 107-k ; 36-$
print(s.translate(table))   # I'm not only li$e Python, but *lso li$e Kotlin.

table1 = s.maketrans('ak', '*$', 'P te')   # {97: 42, 107: 36, 80: None, 32: None, 116: None, 101: None}
print(s.translate(table1))  # 

练习1:统计字符串出现的次数

s = input("请输入一个字符串:")

while True:
    subStr = input('请输入要统计的字符串:')
    if subStr == 'exit()':
        break
    i = 0
    count = 0
    while i < len(s):
        index = s.find(subStr, i)
        if index > -1:
            count += 1
            i = index + len(subStr)
        else:
            break;
    print('"{}"在字符串"{}"中出现了{}次。'.format(subStr, s, count))

练习2:生成一个正三角形

方法一:

n = int(input("要生成多少行:"))

# 底边宽度: 2n-1
for i in range(1, n + 1):
    print("{}".format((2 * i - 1) * '*').center(2 * n-1))

方法二:

n = int(input("要生成多少行: "))

for i in range(1, n + 1):
    if i == n:
        print('{}{:*<{char}}'.format('', '', char=(2 * i - 1)))
    else:
        print('{:{blank}}{:*<{char}}'.format('', '', blank=(n-i), char=(2 * i - 1)))
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 158,560评论 4 361
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,104评论 1 291
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 108,297评论 0 243
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 43,869评论 0 204
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,275评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,563评论 1 216
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,833评论 2 312
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,543评论 0 197
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,245评论 1 241
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,512评论 2 244
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,011评论 1 258
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,359评论 2 253
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,006评论 3 235
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,062评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,825评论 0 194
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,590评论 2 273
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,501评论 2 268

推荐阅读更多精彩内容