05character_string

字符串:基本操作

s1 = "I love python"
print(s1[7])
print(s1[11])
print(s1[15])

p
o



---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

<ipython-input-3-1edf35eec0a4> in <module>
      2 print(s1[7])
      3 print(s1[11])
----> 4 print(s1[15])


IndexError: string index out of range
# 利用分片截取字符串的子字符串
print(s1[7:13])
print(s1[7:])
print(s1[::2])
python
python
Ilv yhn
s2 = "a b c d e f g"
print(s2[::2])
abcdefg
s3 = "abc"
print(s3*10)
abcabcabcabcabcabcabcabcabcabc
print("python" in s1)
print("java" in s1)
print("java" not in s1)
True
False
True
print(len(s1))
print(max(s1))
print(min(s1))
13
y
  • 字符串格式化基础
    • 字符串格式化:静态和动态两部分。Hello Bill Hello 李宁 Hello 张三。Hello param_name 模板。字符串格式化就是把一个或多个值替换另一个字符串的某个标记。%:格式化字符串。
# 定义一个模板,%s:字符串
formatStr = "Hello %s,Today is %s, Are there any activities today?"
# 准备要替换标记的值
values = ("John","Wednesday")
# step3:替换标记
print(formatStr % values)
Hello John,Today is Wednesday, Are there any activities today?
# %f %d
from math import pi
formatStr = "PI是圆周率,PI的值是%.2f(保留小数点后%d位)"
values1 = (pi,2)
print(formatStr % values1 )
PI是圆周率,PI的值是3.14(保留小数点后2位)
formatStr1 = "这件事的成功率是%d%%,如果有%s参与的话,成功率会提升至%d%%。" # 如果要输出“%”需要在后面加两个%。
values2 = (56,"John",70) # 元组的元素个数必须与格式化模板中的标记的数量要一样。
print(formatStr1 % values2)
这件事的成功率是56%,如果有John参与的话,成功率会提升至70%。

用Template类格式化字符串

标记

  • $name $age $price
  • 用什么方式来格式化字符串:substitute
from string import Template
template1 = Template("$lang是我最喜欢的编程语言,$lang非常容易学习,而且功能强大。")
print(template1.substitute(lang = "python"))
python是我最喜欢的编程语言,python非常容易学习,而且功能强大。
template2 = Template("${s}stitute")
print(template2.substitute(s = "sub"))
substitute
template3 = Template("$dollar$$相当于多少$pounds")
print(template3.substitute(dollar = 20,pounds = "英镑"))
20$相当于多少英镑
template4 = Template("$dollar$$相当于多少$pounds")
data = {}
data['dollar'] = 100
data['pounds'] = '英镑'
print(template4.substitute(data))
100$相当于多少英镑

使用format方法格式化字符串

标记(格式化参数):{…}

如何进行格式化:“template”.format(…)

# 按顺序来指定格式化参数值
s1 = "Today is {},the temperature is {} degrees."
print(s1.format("saturday",30))
Today is saturday,the temperature is 30 degrees.
# 使用命名格式化参数
s2 = "Today is {week},the temperature is {degree} degrees."
print(s2.format(week = "sunday",degree = 21))
print(s2.format(degree = 21,week = "sunday"))
Today is sunday,the temperature is 21 degrees.
Today is sunday,the temperature is 21 degrees.
# 混合使用顺序格式化参数和命名格式化参数
s3 = "Today is {week}, {},the {} temperature is {degree} degrees"
print(s3.format("abcd",1234,degree = 43, week = "sunday"))  #print(s3.format("abcd",degree = 43,1234, week = "sunday"))会抛出异常。
Today is sunday, abcd,the 1234 temperature is 43 degrees
# 使用序号格式化参数
s4 = "Today is {week},{1}, the {0} temperature is {degree} degrees."
print(s4.format("abcd",1234,degree=44,week="sunday"))
Today is sunday,1234, the abcd temperature is 44 degrees.
s4 = "Today is {week},{1}, the {1} temperature is {degree} degrees."
print(s4.format("abcd",1234,degree=44,week="sunday"))
Today is sunday,1234, the 1234 temperature is 44 degrees.
# 获取列表中的指定值。
fullname = ["Bill","Gates"]
s5 = "Mr.{name[1]}"
print(s5.format(name = fullname))
Mr.Gates
fullname = ["Bill","Gates"]
s5 = "Mr.{name[1]}"
print(s5.format(name=["Jackson","Tom"]))
Mr.Tom
import math
s6 = "The {mod.__name__} module defines the value {mod.pi} for PI"
print(s6.format(mod = math))
The math module defines the value 3.141592653589793 for PI

更进一步控制字符串格式化参数

字符串格式化类型符

repr函数 repr(‘a’) = ‘a’ str(‘a’) = a

a 将字符串按Unicode编码输出

b 将一个整数格式化为一个二进制数

c 将一个整数解释成ASCII

d 将整数格式化为十进制数

e/E 科学计数法表示

f/F 将一个整数格式化为浮点数,(nan和inf)转换为小写

g/G 会根据整数值的位数,在浮点数和科学计数之间切换,在整数位超过6位时,与e相同,否则与f相同。

o 将一个整数格式化为八进制

s 按原样格式化字符串

x\X 将一个整数格式化为十六进制数

% 将一个数值格式化为百分比格式

s1 = "原样输出:{first!s} 调用repr函数:{first!r} 输出Unicode编码:{first!a}"
print(s1.format(first = "中"))
原样输出:中 调用repr函数:'中' 输出Unicode编码:'\u4e2d'
# 将一个整数按浮点数格式输出
s2 = "整数:{num}  浮点数: {num:f}"
print(s2.format(num=123))
整数:123  浮点数: 123.000000
# 进制转换
s3 = "十进制:{num}  二进制:{num:b}  八进制:{num:o}  十六进制:{num:x}"
print(s3.format(num = 78))
十进制:78  二进制:1001110  八进制:116  十六进制:4e
# 将整数按科学计数法输出
s4 ="科学计数法:{num:e}"
print(s4.format(num = 6789))
科学计数法:6.789000e+03
# 将浮点数按百分比输出
s5 = "百分比:{num:%}"
print(s5.format(num = 0.34))
百分比:34.000000%

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

# 让一个数值在宽度为12的范围内输出,如果数值没到12位,左侧填充空格
print("a:{num:12}".format(num = 32))
# create table
print("{header1:10}{header2:15}".format(header1="姓名",header2="年龄"))
print("{cell11:10}{cell12:6}".format(cell11 = "Bill",cell12 = 43))
print("{cell21:15}{cell22:1}".format(cell21 = "Mike",cell22 = 34))
a:          32
姓名        年龄             
Bill          43
Mike           34
from math import pi
print("float number:{pi:.3f}".format(pi = pi))
print("float number:{pi:20.4f}".format(pi = pi))
float number:3.142
float number:              3.1416
# 截取字符串
print("{msg:.5}".format(msg= "Hello World"))
Hello
# 千位分隔符
print("One googol is {:,}".format(10**100))
One googol is 10,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000,000

符号、对齐和用0填充

from math import pi
print("{pi:012.3f}".format(pi = pi))
print("{pi:#12.3f}".format(pi = pi))

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

字符串方法:center

print("<" + "hello".center(30) + ">")
print("<{:^30}>".format("hello"))
print("<" + "hello".center(20,"*") + ">")
print("<{:*^20}>".format("hello"))
<            hello             >
<            hello             >
<*******hello********>
<*******hello********>

字符串方法:find

s = "hello world"
print(s.find("world"))
print(s.find("abc"))
print(s.find("o"))
print(s.find("o",6))
print(s.find("l",5,9))
print(s.find("l",5,10))
6
-1
4
7
-1
9

字符串方法:join

用于连接序列中的元素,split方法。

list = ["a","b","c","d","e"]
s = '*'
print(s.join(list))
print("@".join(list))
a*b*c*d*e
a@b@c@d@e
dirs = '','usr','local','nginx',''
linuxPath = '/'.join(dirs)
print(linuxPath)
windowPath = 'C;' + '\\'.join(dirs)
print(windowPath)
/usr/local/nginx/
C;\usr\local\nginx\

字符串方法:split方法

s1 = "a b c d e f"
print(s1.split())
['a', 'b', 'c', 'd', 'e', 'f']
s2 = "a*b*c*d*e"
print(s2.split("*"))
['a', 'b', 'c', 'd', 'e']
path = "/urs/local/nginx"
pathList = path.split('/')
print(pathList)
['', 'urs', 'local', 'nginx']
windowPath = "D:" + "\\".join(pathList)
print(windowPath)
D:\urs\local\nginx

字符串方法:lower、upper、和capwprds函数

print("hello".upper())
print("HELLO".lower())
HELLO
hello
list = ["Python","Ruby","Java","KOTLIN"]
if "kotlin" in list:
    print("找到kotlin了")
else:
    print("未找到kotlin")
未找到kotlin
for lang in list:
    if "kotlin" == lang.lower():
        print("找到kotlin了")
        break;
        
找到kotlin了
from string import capwords
s = "i not only like Python, but also like kotlin"
print(capwords(s))
I Not Only Like Python, But Also Like Kotlin

字符串方法:replace和strip

s = "abcdef"
print(s.replace("a","12345"))
12345bcdef
print(s.replace("xyz","aa"))
abcdef
# strip函数
print("   geeko    ri.com    ".strip())
geeko    ri.com
langList = ["python","java","ruby","scala","perl"]
lang = "   python   "
if lang in langList:
    print("找到了python")
else:print("未找到python")    
    
if lang.strip() in langList:
    print("找到python")
else:
    print("未找到python")
未找到python
找到python
s = "***  $$*   Hello * World   ***$$$     *"
print(s.strip(" *$"))
Hello * World

字符串方法:translate和maketrans

  • translate:替换单个字符
s = "I not only like python,but also like kotlin."
table = s.maketrans("ak","*$")
print(table)
print(s.translate(table))
{97: 42, 107: 36}
I not only li$e python,but *lso li$e $otlin.
table1 = s.maketrans("ak","*$"," ")
print(table1)
{97: 42, 107: 36, 32: None}
print(s.translate(table1))
Inotonlyli$epython,but*lsoli$e$otlin.

练习题

  • 1.编写一个python程序,从控制台输入一个字符串(保存到变量s中),然后通过while循环不断输入字符串(保存到变量subStr中),并统计subStr在s中出现的次数,最后利用format方法格式化统计结果。
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))        
            
请输入一个字符串:I love python.
请输入要统计的字符串:l
'l'在'I love python.'中出现了1次
请输入要统计的字符串:o
'o'在'I love python.'中出现了2次
请输入要统计的字符串:exit
'exit'在'I love python.'中出现了0次
请输入要统计的字符串::exit
s1 = "Ib love python."
subStr = "Ib"
index = s1.find(subStr,0)
print(index)
0
  • 2.利用format方法生成一个星号三角形。
print("{:<10}{:*<1}".format(" ",""))
print("{:<9}{:*<3}".format(" ",""))
print("{:<8}{:*<5}".format(" ",""))
print("{:<7}{:*<7}".format(" ",""))
print("{:<6}{:*<9}".format("",""))
print("{:<5}{:*<11}".format("",""))
print("{:<4}{:*<13}".format("",""))
print("{:<3}{:*<15}".format("",""))
print("{:<2}{:*<17}".format("",""))
print("{:<1}{:*<19}".format("",""))
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************
floorStr = input('请输入一个层数:')
floor = int(floorStr)
num = floor * 2 - 3
while floor > 0:
    print("{:<{a}}{:*<{b}}".format(" ","",a = floor,b = (num - (floor-2)*2)))
    floor -= 1
请输入一个层数:10
          *
         ***
        *****
       *******
      *********
     ***********
    *************
   ***************
  *****************
 *******************

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值