第四章:字符串

第1讲:初窥字符串

  1.格式化字符串的格式

   左侧%右侧

   左侧:放置1个字符串

   右侧:放上希望被格式化的值

fomat = "hello,%s,%s enough for ya!!"
values = ("world!","Hot")
# 字符串格式化时,如果对于的值是多个,值应该放在元祖中
print(fomat % values)

结果:
hello,world!,Hot enough for ya!!

   2.基本的转化说明符

  • %字符:标记转换说明的开始
  • 转换标志(可选):- 表示左对齐;+ 表示在转换值之前要加上正负号;“ ” 表示正数之前保留空格;0表示转换值若位数不够用0填充
  • 最小字段宽度(可选):转换后的字符串至少应该具有该值指定的宽度
  • 点(.)后跟精度(可选):如果转换的为实数,精度值就表示出现在小数点后的位数,如果转换的是字符串,那么该数字就表示最大字段宽度,如果是*,那么精度会从元组中读取。

   简单格式化

# 简单转化
print("%s plus %s equal %s" % (1,2,3))
print("Price of eggs: $%d" % 42)
print("Price of eggs: $%x" % 42)

import math
print(math.pi)
print("pi:%f ..." % math.pi)

结果:
1 plus 2 equal 3
Price of eggs: $42
Price of eggs: $2a
3.141592653589793
pi:3.141593 ...

  字段的宽度与精度

# 字段宽度与精度
from math import pi
# 10f表示宽度为10的浮点型
print("%10f" % pi)
# 10表示宽度,.后的2表示精度
print("%10.2f" % pi)
print("%.2f" % pi)
# 点(.)后跟精度值(可选):如果转化的实数
# 精度值就表示出现在小数点后的位数
# 如果转化的是字符串,那么该数字就表示最大字段宽度
# 如果是“*”,那么精度会从元组中读取
print("%10.5s" % "python is great!")
print("%.5s" % "python is great!")
print("%*.*s" % (10,6,"python is great!"))
print("%.*s" % (3,"python is great!"))

结果:
  3.141593
      3.14
3.14
     pytho
pytho
    python
pyt

   符号、对齐、用0填充

# 符号、对齐和用0填充
from math import pi
# "010"第1个0不是意味着八进制
# 表示宽度为10,并且用0填充空位
print("============0填充空位=============")
print("%10f" % pi)
print("%010f" % pi)
print("%10.2f" % pi)
print("%010.2f" % pi)
print("============'-'表示左对齐=============")
print("%10.2f" % pi)
print("%-10.2f" % pi)
print("============""表示正数前加上空格=============")
print("============"+"表示在转换之前加上正负号=============")
print(("% 5d" % 10) + "\n" + ("%5d" % -10))
print(("%+5d" % 10) + "\n" + ("%+5d" % -10))

结果:
============0填充空位=============
  3.141593
003.141593
      3.14
0000003.14
============'-'表示左对齐=============
      3.14
3.14      
============表示正数前加上空格=============
============表示在转换之前加上正负号=============
   10
  -10
  +10
  -10

 第2讲:字符串的方法

  1. find方法

   find可以在一个字符串中查找子串,返回子串在父串中所占位置最左端的索引

   find(sub,start,end)

# find方法,返回字符串最左端的索引
# 如果没找到则返回-1
title = "Monty python's Flying Circus!"
print(title.find("python"))
print(title.find("python",7))
print(title.find("python",6,20))

结果:
6
-1
6

   2.join方法:将字符串串联起来

   注意:连接的元素都是字符串

# join方法
# 连接的序列元素必须是字符串
student_names = ["Alice","Bob","Bela"]
print("+".join(student_names))
#numbers = [1,2,3]
#print("+".join(numbers)) # 该语句会保存,原因:连接的序列元素必须是字符串
dirs = ("","home","bob")
dirs1 = ["","home","bob"]
print("/".join(dirs))
print("/".join(dirs1))
print("c:"+"\\".join(dirs))

结果:
Alice+Bob+Bela
/home/bob
/home/bob
c:\home\bob

   3.spit方法:将字符串切割为列表中的元素

   默认spit()不加参数,是根据空格进行切分

sentence = "Hello world!"
print(sentence.split())
numbers = "1+2+3+4"
print(numbers.split())
print(numbers.split("+"))

结果:
['Hello', 'world!']
['1+2+3+4']
['1', '2', '3', '4']

   4.lower()将字符串转换为小写

names = "Hello World!"
print(names.lower())
student_names = ["alice","bob","bela"]
student_name = "Bela"

if student_name.lower()in student_names:
    print(True)
else:
    print(False)

结果:
hello world!
True

   5.replace:将指定的字符串替换为目标字符串

   replace(oldsub.newsub.n)n指替换字符串的个数

   strip()去除字符串两侧空格或指定字符串

# replace 方法
print("This is an apple.".replace("apple","orange"))
print("This is an apple apples.".replace("apple","orange"))
# replace 第3个参数,指定替换次数
print("This is an apple apples.".replace("apple","orange",1))
# strip方法
name = " Bela "
names = ["alice","leo","bela"]
namebak = name.lower()
if namebak.strip() in names:
    print(True)
else:
    print(False)

str = "*** python * for program language!***"
print(str.strip("*"))
print("*** python * for program language!***".strip("!"))
print("*** python * for program language!***".strip("*"))


结果:
True
 python * for program language!
*** python * for program language!***
 python * for program language!

   6. translate 同时替换多个字符

    注意:一般与maketrans函数结合使用

   maketrans方法:接收2个参数,且是2个等长的参数,第1个参数是被转换的字符串,第2个参数是要转换的目标

   translate方法:只有1个参数,必须是dict类型

  列表:[ ]、元祖:( )、字典:{ }

str = "this is a string demo……wow!!"
intab = "aeiou"
outtab ="12345"
trantab = str.maketrans(intab,outtab)
print(trantab)
print(str.translate(trantab))

结果:
{97: 49, 101: 50, 105: 51, 111: 52, 117: 53}
th3s 3s 1 str3ng d2m4……w4w!!

 第3讲:字符串格式化案例

 案例:使用给定的宽度,打印格式后的水果名称和价格

# 字符串格式案例
# 使用给定的宽度,打印格式后的水果名称和价格
width = int(input("please input width:"))
price_width = 8
item_width = width - price_width
print("=" * width)
# header_format 表示表头,为字符串
# conFormat 表示内容,*.2f 价格为实数,精确到小数后2位
header_format = "%-*s%-*s"
conFormat = "%-*s%-*.2f"
print(header_format % (item_width,"Name",price_width,"Price"))
print("-" * width)
print(conFormat % (item_width,"Apple",price_width,5.89))
print(conFormat % (item_width,"Orange",price_width,4.123))
print(conFormat % (item_width,"Banana",price_width,3.1))


结果:

please input width:20
====================
Name        Price   
--------------------
Apple       5.89    
Orange      4.12    
Banana      3.10    

猜你喜欢

转载自www.cnblogs.com/ling07/p/10681046.html