[转载] python 字符串(string)

参考链接: Python字符串String

字符串 

什么是字符串? 

字符串是Python中最长用的数据类型。我们可以使用引号('或")来创建字符串。事实上,在Python中,加了引号的字符都被认为是字符串。 

name = "Changsh" #双引号

age ="5000" #只要加双引号就是字符串

age_1 =5000 #不加,整形

msg ="""I'm in Changsha"""#三双引号

msg_1 ='''I' m in Hengyang'''#三单引号

hometowm ='Changsha' #单引号

print(type(name),type(age),type(age_1),type(msg),type(msg_1),type(hometown),sep="|")

 

多引号有什么作用呢?作用就是多行字符必须用多引号。 

msg ="""

轻轻的我走了,

正如我轻轻的来;

我轻轻的招手,

作别西天的云彩。

"""

print(msg)

 

字符串运算及操作 

数字可以进行加减乘除等运算,字符串呢?让我大声告诉你,也能?what?是的,但只能进行"相加"和"相乘"运算。 

(1)拼接(+) 

>>> a="Hello"

>>> b="Python"

>>> a+b

'HelloPython'

 

注意,字符串的拼接只能是对方都是字符串,不能跟数字或其它类型拼接。 

>>>age_1=5000

>>>name+age_1

Traceback (most recent call last):

 File"<stdin>",line 1,in <module>

 TypeError:must be str,not int

 

(2)重复(*) 

>>> a="Hello"

>>> a*3

'HelloHelloHello'

 

(3)字符串索引([]以及切片([::])) 

 

#########0123456789012345367890123456789

>>> a = "Life is short,I use python"

>>>len(a)

27

>>> #索引

>>>a[0]

'L'

>>>a[-1]

'n'

>>> #切片

...

>>> a[:13] #从第一个元素开始,一直到索引值为12的元素

'Life is short'

>>> a[15:] #从索引值为15的元素开始,一直到最后

'I use python'

>>> a[15::2] #从索引值为15的元素开始,步长为2,即每次跳过一个元素,一直到最后

'Iuepto'

>>> a[::-1] #逆序输出

'nohtyp esu I ,trohs si efiL'

 

 

(4)大小写转换 

str.lower():转小写str.upper():转大写str.swapcase():大小写对换str.capitalize():字符串首为大写,其余小写str.title():以分隔符为标记,首字符为大写,其余为小写 

>>> a="Life is short, I use python"

>>> a.lower() #将所有大写字符转换为小写字符

'life is short, i use python'

>>> a.upper() #将所有小写字符转换为大写字符

'LIFE IS SHORT, I USE PYTHON'

>>> a.swapcase() #将大小写互换

'lIFE IS SHORT, i USE PYTHON'

>>> a.capitalize() #将首字符大写

'Life is short, i use python'

>>> a.title() #返回标题化的字符串

'Life Is Short, I Use Python'

>>>

 

应用:验证码 

s_str = "AbDc"

inputofyou = input("请输入密码,不区分大小写:")

if s_str.lower() == inputofyou.lower():

    print("输入成功。")

else:

    print("输入错误,请重新输入。")

 

(5字符串格式输出对齐 

str.center()居中str.ljust()左居中str.rjust()右居中str.zfill()左居中,以0填充长度 

>>> a="Life is short, I use python"

>>> a.center(35,'*') #返回一个原字符串居中,并使用空格填充至长度width的新字符串

'****Life is short,I use python****'

 

>>> a.ljust(35,'*') #返回一个原字符串左对齐,并使用空格填充至长度width的新字符串

'Life is short, I use python********'

 

>>> a.zfill(35) # 返回长度为width的字符串,原字符串string右对齐,前面填充0,只有一个参数

'00000000Life is short, I use python'

 

>>> a.rjust(35, '*')# 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串

'********Life is short, I use python'

 

(6)删除指定参数 

str.lstrip()str.rstrip()str.strip() 

>>> a="****Life is short, I use python****"

>>> a.lstrip("*")

'Life is short, I use python*****'

 

>>> a.rstrip("*")

'****Life is short, I use python'

 

>>> a.strip("*")

'Life is short, I use python'

>>>

 

(7)计数 

Excel表格中: 

=COUNTIF(B2:B31,">=30")/COUNT(B2:B31)

 

python中: 

>>> a= "Life is short, I use python"

>>> a.count('i') # 返回str在 string 里面出现的次数

2

 

>>> a.count('i',4,8) # 在索引值为[4,8]的范围内 str 出现的次数

1

>>>

 

(8)字符串搜索定位与替换 

str.find() # 搜索 

>>> a= "Life is short, I use python"

>>> a.find('e') # 查找元素并返回第一次出现的元素的索引值

3

 

>>> a.find('e',18,24) # 查找元素在指定范围内的索引

19

 

>>> a.find('w') # 找不到值返回-1

-1

 

str.index() 

  和find()方法一样,只不过如果str不在string中会报一个异常  

>>> a= "Life is short, I use python"

>>> a.index('e') # 查找元素并返回第一次出现的元素的索引值

3

>>> a.index('e',18,24) # 查找元素在指定范围内的索引

19

>>> a.index('w')

Traceback (most recent call last):

  File "<stdin>",line 1, in <module>

ValueError: substring not found

>>>

 

str.replace() 

>>> a= "Life is short, I use python"

>>> a.replace('I use','You need')#把字符串I use替换成You need

'Life is short, You need python'

>>> a.replace('t','T') #把字符串中的t替换成T

'Life is shorT, I use pyThon'

>>> a.replace('t','T',1) #遇到第一个t就替换成T,后面就不用替换了

'Life is shorT, I use python'

>>>

 

(9)字符串条件判断 

isalnum(),字符串由字母或数字组成,isalpha(),字符串只由字母组成,isdigit(),字符串只由数字组成 

In [1]: a = "abc123"

 

In [2]: b = "ABC"

 

In [3]: c = 123

 

In [4]: a.isalnum()

Out[4]: True

 

In [5]: a.isalpha()

Out[5]: False

 

In [6]: a.isdigit()

Out[6]: False

 

In [7]: b.isalnum()

Out[7]: True

 

In [8]: b.isalpha()

Out[8]: True

 

In [9]: b.isdigit()

Out[9]: False>>> str = '01234'

 

>>> str.isalnum()                #是否全是字母和数字,并至少有一个字符

True

>>> str.isdigit()                #是否全是数字,并至少有一个字符

True      

 

 

>>> str = 'string'

>>> str.isalnum()                  #是否全是字母和数字,并至少有一个字符

True

>>> str.isalpha()                  #是否全是字母,并至少有一个字符 

True

>>> str.islower()                  #是否全是小写,当全是小写和数字一起时候,也判断为True

True

 

>>> str = "01234abcd"

>>> str.islower()                  #是否全是小写,当全是小写和数字一起时候,也判断为True

True

  

>>> str.isalnum()                  #是否全是字母和数字,并至少有一个字符

True

 

>>> str = ' '

>>> str.isspace()                  #是否全是空白字符,并至少有一个字符

True

 

>>> str = 'ABC'

>>> str.isupper()                  #是否全是大写,当全是大写和数字一起时候,也判断为True

True

 

>>> str = 'Aaa Bbb'

>>> str.istitle()                  #所有单词字首都是大写,标题 

True

 

>>> str = 'string learn'

>>> str.startswith('str')                 #判断字符串以'str'开头

True

 

>>> str.endswith('arn')                      #判读字符串以'arn'结尾

True

 

(10)制表符转化 

str.expandtabs() 

>>> a ="L\tife is short, I use python"

>>> a.expandtabs() # 默认将制表符转化为8个空格

'L        ife is short, I use python'

 

>>> a.expandtabs(4) # 加上参数,即制表符转化为对应个数的空格

'        ife is short, I use python'

>>>

 

(11)ASCII码和字符的转化 

chr():用一个范围在range(256)内的(就是0~255)整数做参数,返回一个对应的字符。ord():将一个ASCII字符转换为对应的数字 

>>> chr(65)

'A'

 

>>> ord('a')

97

 

(12)字符串分割变换 

join():使用指定字符对字符串进行分割split():以指定字符分隔序列且去除该字符partition():以指定字符分隔序列且包含该字符 

#join

>>> str="learn string"

>>> '-'.join(str)

'l-e-a-r-n- -s-t-r-i-n-g'

>>> li=["learn","string"]

>>> '+'.join(str)

'l+e+a+r+n+ +s+t+r+i+n+g'

>>> '-'.join(li)

'learn-string'

 

#split

>>> str.split('n')

['lear', ' stri', 'g']

>>> str.split('n',1)

['lear', ' string']

>>> str.rsplit('n')

['lear', ' stri', 'g']

>>> str.rsplit('n',1)

['learn stri', 'g']

>>> str.splitlines()

['learn string']

>>> str.partition('n')

('lear', 'n', ' string')

>>> str.rpartition('n')

('learn stri', 'n', 'g')

 

补充: 

string模块 

查看: 

>>> import string

>>> dir(string)

['Formatter', 'Template', '_ChainMap', '_TemplateMetaclass', '__all__', '__builtins__', '__cached__', '__doc__', '__file__', '__loader__', '__name__', '__package__', '__spec__', '_re', '_string', 'ascii_letters', 'ascii_lowercase', 'ascii_uppercase', 'capwords', 'digits', 'hexdigits', 'octdigits', 'printable', 'punctuation', 'whitespace']

>>> string.ascii_letters

'abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ'

>>>

 

string模块中的capwords()函数功能: 

1.将每个单词首字母置为大写2.将每个单词除首字母外的字母均置为小写;3.将词与词之间的多个空格用一个空格代替4.其拥有两个参数,第二个参数用以判断单词之间的分割符,默认为空格。 

string常用方法: 

>>> string.digits

'0123456789'

>>> string.hexdigits

'0123456789abcdefABCDEF'

>>> string.octdigits

'01234567'

>>> string.printable

'0123456789abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~ \t\n\r\x0b\x0c'

>>> string.punctuation

'!"#$%&\'()*+,-./:;<=>?@[\\]^_`{|}~'

>>>

 

"%"是Python风格的字符串格式化操作符,非常类似C语言里的printf()函数的字符串格式化(C语言中也是使用%)。 

下面整理了一下Python中字符串格式化符合: 

格式化符号说明%c转换成字符(ASCII 码值,或者长度为一的字符串)%r优先用repr()函数进行字符串转换%s优先用str()函数进行字符串转换%d / %i转成有符号十进制数%u转成无符号十进制数%o转成无符号八进制数%x / %X转成无符号十六进制数(x / X 代表转换后的十六进制字符的大小写)%e / %E转成科学计数法(e / E控制输出e / E)%f / %F转成浮点数(小数部分自然截断)%g / %G%e和%f / %E和%F 的简写%%输出% (格式化字符串里面包括百分号,那么必须使用%%)

这里列出的格式化符合都比较简单,唯一想要强调一下的就是"%s"和"%r"的差别。 

看个简单的代码: 

>>> a=15

>>> print(("%d to he is %X")%(a,a))

15 to he is F

>>> "%f" % 15

'15.000000'

>>> "%e" % 15000

'1.500000e+04'

>>> "%d" % 100

'100'

>>> "%d%%" % 100

'100%'

>>>

 

你怎么实现呢?你会发现,用字符拼接的方式还难实现这种格式的输出,所以一起来学一下新姿势 

只需要把要打印的格式先准备好, 由于里面的 一些信息是需要用户输入的,你没办法预设知道,因此可以先放置个占位符,再把字符串里的占位符与外部的变量做个映射关系就好啦。 

name = input("Name:")

age = input("Age:")

job = input("Job:")

hobbie = input("Heobbie:")

 

info='''

---info of%s---

Name :\t %s

Age  :\t %s

job  :\t %s

Hobbie:\t %s

------end------

'''%(name,name,age,job,hobbie) #这行的%号就是把前面的字符串与括号后面的变量关联起来

print(info)

 

 

作业: 

demo:名片打印 

要求:输入姓名、年龄、工作和爱好,按下列格式输出: 

---info of Linus---

Name  :  Linus

Age   :  18

job   :  IT

Hobbie:  Read

-------end------

 

作业:上述名片打印拓展成存储多人信息的列表。

        [

 

        ["Linus", 18,  "IT", "Read"],

 

        ["Tom", 17, "IT", "Sing"],

 

        ....

 

        ]

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值