python字符串

字符串

字符串格式

使用string模块中的字符串模板Template对象,使用substitute()方法举例

#!/usr/bin/env python
#-*- coding:utf8 -*-

# 字符串模板
from string import Template

s = Template('hi,$name ! $name is learning $language')
print(s.substitute(name='sihye', language='english'))

d = {'name': 'hwang', 'language': 'chinese'}
print(s.substitute(d))
# 使用$$来显示$
s = Template('This book ($bname) is 17$$')
print(s.substitute(bname='korean'))

print('--------------')
print('--------------')
print('--------------')
# 位置参数
print('{0} is a {1}'.format('hwang','girl'))
print('{} is a {}'.format('hwang','girl'))
print('{0} is a {1},i love {0}'.format('hwang','girl'))
# 关键字参数
print('{name} is a {sex}'.format(name = 'hwang', sex = 'girl'))

# 下标参数
person = ['hwang', 'girl']
print('{0[0]} is a {0[1]}'.format(person))

# 填充与对齐
# ^、<、>分别是居中、左对齐、右对齐,后面带宽度
# :号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
print('{:-^7}'.format('hello'))
print('{:-<7}'.format('hello'))
print('{:->7}'.format('hello'))
print('{:>7}'.format('china'))

# 浮点数精度
# 小数点后保留几位数
print('{:.4f}'.format(3.14151926))
# 冒号后面跟上填充数,默认空格,带上总共的位数.小数点后精确度
print('{:0>10.4f}'.format(3.1415926))
print('{:>10.4f}'.format(3.1415926))

# 千位分隔符
print('{:,}'.format(100009992039))

运行:

# python touple.py 
hi,sihye ! sihye is learning english
hi,hwang ! hwang is learning chinese
This book (korean) is 17$
--------------
--------------
--------------
hwang is a girl
hwang is a girl
hwang is a girl,i love hwang
hwang is a girl
hwang is a girl
-hello-
hello--
--hello
  china
3.1415
00003.1416
    3.1416
100,009,992,039

字符串的内建函数

#!/usr/bin/env python
#-*- coding:utf8 -*-

A = 'HI !'
Aa = 'Hi !'
a = 'hi !'
# 整体小写
print(A.lower())
# 整体大写
print(a.upper())
# 大小写互换
print(Aa.swapcase())
# 首字母大写
print(a.capitalize())

B = 'nice'
# 输出width个字符,S左对齐,不足部分用fillchar填充,默认的为空格。
# 格式: S.ljust(width,[fillchar]) 
# 左对齐
print(B.ljust(10, '-'))
# 右对齐
print(B.rjust(10, '-'))
# 中间对齐
print(B.center(10, '-'))

C = 'australia'
print(str(C))
print('在{0}单词中,下标2-6内a是在第{1}位'.format(C, C.find('a', 2, 6)))
print('在{0}单词中,出现的第一个a是在第{1}位'.format(C, C.find('a')))
print('在{0}单词中,最后出现的a是在第{1}位'.format(C, C.rfind('a')))
print('在{0}单词中,下标2-6内的a总共出现{1}次'.format(C, C.count('a', 2, 6)))
print('在{0}单词中,a总共出现{1}次'.format(C, C.count('a')))
# 把S中的oldstar替换为newstr,count为替换次数
# 格式:S.replace(oldstr, newstr, [count]) 
print('在{0}单词中,将{1},全部替换成{2},最后结果为{3}'.format(C, 'a', 'A',C.replace('a', 'A')))
print('在{0}单词中,将{1},替换2个成{2},最后结果为{3}'.format(C, 'a', 'A',C.replace('a', 'A', 2)))

D = 'huangshihui'
print(D.strip('shi'))
print(D.lstrip('shi'))
print(D.rstrip('shi'))

运行

hi !
HI !
hI !
Hi !
nice------
------nice
---nice---
australia
在australia单词中,下标2-6内a是在第5位
在australia单词中,出现的第一个a是在第0位
在australia单词中,最后出现的a是在第8位
在australia单词中,下标2-6内的a总共出现1次
在australia单词中,a总共出现3次
在australia单词中,将a,全部替换成A,最后结果为AustrAliA
在australia单词中,将a,替换2个成A,最后结果为AustrAlia
uangshihu
uangshihui
huangshihu

列表

使用append()方法动态扩展列表,增加单个对象

# 定义一个字符串
words = 'international'
# 定义一组英语元音列表
a = ['a', 'e', 'i', 'o', 'u']
# 定义一个空列表
b = []
c = []
# 输出列表的元素个数
print(len(b))
# 用In来检查成员关系,p是words单次中的字母
for p in words:
    # 判断 若 b也在a中
    if p in a:
        # 在b列表中插入符合条件的p[也就是p in a]
        b.append(p)
        # 再次输出b列表的长度
    else:
        # 匹配的是在单词中不是元音的字母,插入到c列表中
        c.append(p)
print(len(b))
# 打印b列表,可以发现从单次第一个字母开始的顺序,以此打印了出现的元音字母
print(b)
print(c)
0
6
['i', 'e', 'a', 'i', 'o', 'a']
['n', 't', 'r', 'n', 't', 'n', 'l']

去除重复字母

# 定义一个字符串
words = 'international'
# 定义一组英语元音列表
a = ['a', 'e', 'i', 'o', 'u']
# 定义一个空列表
c = []
d = []
# 用In来检查成员关系,p是words单次中的字母
for p in words:
    # 判断 若 b也在a中
    if p in a:
        # 去除重复字母
        if p not in d:
            d.append(p)
            continue
print(d)
['i', 'e', 'a', 'o']

匹配

# 定义一个句子
sentence = 'hello,welcome to the dysney land'
print(sentence)
# 让用户输入一个单次
word = input('please enter the words that u want to search : ')
# 定义一个空列表
found = []
# 定义p元素在句子中
for p in sentence:
    # 判断 p同时也在输入的word中
    if p in word:
        # 向found集合中插入p
        found.append(p)
        # 循环继续
        continue
# 判断结果是否为空
if len(found) > 0:
    # 打印查询值在句子中出现的次数
    print('num is : {}'.format(len(found)) )
else:
    # 若没有匹配值返回空
    print('sorry,null')

运行:

hello,welcome to the dysney land
please enter the words that u want to search : u
sorry,null

hello,welcome to the dysney land
please enter the words that u want to search : want
num is : 6

remove()方法从列表中制定数据值删除,同时列表长度-1

注意: remove()中的值并不是索引,而是要删除的值

# 定义一个数字列表
num = ['1', '2', '3', '4']
print(num)
a = ['3', '6']
# p去迭代,p在a中,判断p若也在num中,则删除p,继续迭代
for p in a:
    if p in num:
        num.remove(p)
print(num)
['1', '2', '3', '4']
['1', '2', '4']

pop()根据索引值去弹出对象

会根据对象的索引值从现有列表删除和返回一个对象,调用pop时没有制定索引值,将删除和返回列表的最后一个对象,如果制定了索引值,会弹出该索引值位置上的对象。

# 定义一个数字列表
num = ['1', '2', '3', '4', '3', '5', '6']
print(num)
# 默认情况
fa = num.pop()
print(num)
# 带索引值
fb = num.pop(0)
print(num)
# 带多个索引值
print('默认是{0},带索引是{1}'.format(fa, fb))

运行:

['1', '2', '3', '4', '3', '5', '6']
['1', '2', '3', '4', '3', '5']
['2', '3', '4', '3', '5']
默认是6,带索引是1

extend 接收列表,将其中各个对象增加到现有列表,即将两个列表合并

# 定义一个数字列表
num = [1,2,3,4,5]
print(num)
# 默认情况
fa = num.extend([3, 4])
print(num)

运行:

[1, 2, 3, 4, 5]
[1, 2, 3, 4, 5, 3, 4]

在列表任意位插入对象

insert()方法,将一个对象插入到现有列表中指定索引值前面,可插入列表开头,但是不能插在末尾,因为这是append方法的工作。
格式 insert(要插在那个对象之前该对象的索引值,要插入的对象)

# 定义一个数字列表
num = [1,2,3,4,5]
print(num)
# 默认情况
fa = num.insert(0,[4,2])
fb = num.insert(0, 'w')
fc = num.insert(4,0)
print(num)

运行:

[1, 2, 3, 4, 5]
['w', [4, 2], 1, 2, 0, 3, 4, 5]

列表练习:

# 定义一个字符串
phrase = 'Dont panic'
print(phrase)
# 将字符串转化为列表
plist = list(phrase)
# 将列表重新转化为新的字符串
new_phrsa = ''.join(plist)
print(new_phrsa)
words = ['o', 'n', 't', 'p', 'a']
new_list = []
for p in plist:
    if p in words:
        if p not  in new_list:
            new_list.append(p)
new_list.pop(4)
new_list.insert(3, 'a')
new_words = ''.join(new_list)
print(new_words)

run:

Dont panic
Dont panic
ontap

posted @ 2020-04-03 16:31  sihte  阅读(175)  评论(0编辑  收藏  举报