Python3 字符串

Posted yujiaershao

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python3 字符串相关的知识,希望对你有一定的参考价值。

字符串相关的功能详解

 

 

 

  • capitalize:  返回一个首字母大写的字符串


t = (‘heLLo‘)
v = t.capitalize()

print(v)

输出:

Hello

 

  • casefold:返回将字符串中所有大写字符转换为小写后生成的字符串。

    其效果和 lower() 方法非常相似,都可以转换字符串中所有大写字符为小写。

    两者的区别是:lower() 方法只对ASCII编码,也就是‘A-Z’有效,对于其他语言(非汉语或英文)中把大写转换为小写的情况只能用 casefold() 方法。

t = (‘HELLo‘)

v = t.casefold()

print(v)

输出:
hello

 

  • center(self, width, fillchar=None):  内容居中,width:总长度;fillchar:空白处填充内容,默认无 
    t = (‘hello‘)

    v = t.center(20)

    print(v)

    #输出:
           hello        

    t = (‘hello‘)

    v = t.center(20, ‘*‘)

    print(v)

    #输出:

    *******hello********

 

  • count(self, sub, start=None, end=None): 子序列个数,start:开始位置,end:结束位置
t = (‘hello‘)

v = t.count(‘l‘)

print(v)

#输出:
2



  • encode:编码
  • decode:解码

#!/usr/bin/python3

str = "菜鸟教程";
str_utf8 = str.encode("UTF-8")
str_gbk = str.encode("GBK")

print(str)

print("UTF-8 编码:", str_utf8)
print("GBK 编码:", str_gbk)

print("UTF-8 解码:", str_utf8.decode(‘UTF-8‘,‘strict‘))
print("GBK 解码:", str_gbk.decode(‘GBK‘,‘strict‘))

输出:

菜鸟教程
UTF-8 编码: b‘xe8x8fx9cxe9xb8x9fxe6x95x99xe7xa8x8b‘
GBK 编码: b‘xb2xcbxc4xf1xbdxccxb3xcc‘
UTF-8 解码: 菜鸟教程
GBK 解码: 菜鸟教程

 



  • endswith:以xxx结尾
t = ‘Hello‘

v1 = t.endswith(‘o‘)
v2 = t.endswith(‘l‘)

print(v1,v2)
输出:

True False




  • expandtabs:把字符串的tab符号转为空格。

t = ‘username adress age Bob NewYork 12 Lily Shanghai 22‘

v = t.expandtabs(20)

print(v)
输出:

username            adress              age
Bob                     NewYork             12
Lily                   Shanghai            22



  • find(self, sub, start=None, end=None):  寻找子序列位置,如果没找到,返回 -1 
t = ‘Hello‘

v1 = t.find(‘o‘)
v2 = t.find(‘t‘)


print(v1, v2)
输出:

4 -1




  • format:字符串的格式化及填充
v1 = ‘my name is {} ,age {}‘.format(‘hoho‘,18)
v2 = (‘my name is %s ,age %d ‘ % (‘hoho‘ ,18))
print(v1)
print(v2)
输出:

my name is hoho ,age 18
my name is hoho ,age 18

 

 

  • index:跟find()方法一样,只不过如果str不在字符串中会报一个异常.
t = ‘Hello‘

v1 = t.index(‘o‘)

print(v1)
输出:

4

t = ‘Hello‘

v1 = t.index(‘a‘)

print(v1)
输出:

Traceback (most recent call last):
File "C:/Users/ehaier/PycharmProjects/old_boy/基础/t1.py", line 4, in <module>
v1 = t.index(‘a‘)
ValueError: substring not found



  • isalnum :如果字符串至少有一个字符并且所有字符都是字母或数字则返 回 True,否则返回 False
t1 = ‘Hello234_‘
t2 = ‘Hello123‘

v1 = t1.isalnum()

print(v1)

v1 = t2.isalnum()

print(v1)
输出:


False
True

 

  • isalpha:如果字符串至少有一个字符并且所有字符都是字母则返回 True, 否则返回 False

 

t1 = ‘Hello1234‘
t2 = ‘Hello‘

v1 = t1.isalpha()

print(v1)

v1 = t2.isalpha()

print(v1)
输出:

False
True

 

 

 

 

  • isdecimal:如果字符串是否只包含十进制字符返回True,否则返回False。

 

t1 = ‘12.34‘
t2 = ‘1234‘

v1 = t1.isdecimal()

print(v1)

v1 = t2.isdecimal()

print(v1)
输出:

False
True

 

 

  • isdigit: 如果字符串只包含数字则返回 True 否则返回 False..

 

t1 = ‘123345‘
t2 = ‘hello123‘

v1 = t1.isdigit()

print(v1)

v1 = t2.isdigit()

print(v1)
输出:

True
False

 

 

  • isidentifier:是否为标识符/变量名(变量名不能以数字开头)

 

t1 = ‘def‘
t2 = ‘1def‘

v1 = t1.isidentifier()
v2 = t2.isidentifier()

print(v1)
print(v2)
输出;

True
False

 

 

  • islower:是否是小写

 

t1 = ‘hello‘
t2 = ‘Hello‘

v1 = t1.islower()
v2 = t2.islower()

print(v1)
print(v2)
输出:

True
False

 

 

 

  • isnumeric:是否为数字,汉字也可以

 

t1 = ‘二‘
t2 = ‘123‘

v1 = t1.isnumeric()
v2 = t2.isnumeric()

print(v1)
print(v2)

输出:

True
True

 

 

  • isprintable:可打印的,不包括格式化符号

 

t1 = ‘Hello	‘
t2 = ‘Hello‘

v1 = t1.isprintable()
v2 = t2.isprintable()

print(v1)
print(v2)
输出:

False
True

 

 

  • isspace:是否是空格

 


t1 = ‘Hello ‘
t2 = ‘ ‘

v1 = t1.isspace()
v2 = t2.isspace()

print(v1)
print(v2)
输出:

False
True

 

  • istitle: 是否是标题,标题首字母大写

 

t1 = ‘Hello ,everyone!‘
t2 = ‘Hello, Everyone!‘

v1 = t1.istitle()
v2 = t2.istitle()

print(v1)
print(v2)
输出;

False
True

 

 

  • isupper:是否是大写

 

t1 = ‘Hello‘
t2 = ‘HELLO‘

v1 = t1.isupper()
v2 = t2.isupper()

print(v1)
print(v2)
输出:

False
True

 

 

  • join:连接

 

t1 = ‘hello‘
t2 = ‘_‘

v1 = t2.join(t1)

print(v1)
输出:
h_e_l_l_o

 

 

 

  • ljust:左对齐,右填充

 

t1 = ‘hello‘
t2 = ‘‘

v1 = t1.ljust(20,‘*‘)

print(v1)
输出:

hello***************

 

  • lower:转换成小写

 

t1 = ‘HEllo‘
t2 = ‘‘

v1 = t1.lower()

print(v1)
输出:
hello

 

 

  • lstrip:去除左侧字符,不指定时,去除空格

 

t1 = ‘HEllo‘

v1 = t1.lstrip(‘H‘)

print(v1)
输出:
Ello


t1 = ‘   HEllo   ‘

v1 = t1.lstrip()

print(v1)
输出:
HEllo   

 

  • maketrans: 替换
  • translate:转换,需要先做一个对应表,最后一个表示删除字符集合

 

intab = "aeiou"
outtab = "12345"
trantab = str.maketrans(intab, outtab)

str = "this is string example....wow!!!"
print (str.translate(trantab))
输出;
th3s 3s str3ng 2x1mpl2....w4w!!!

 

 

  • partition: 拆分成3个字符串

 

t1 = ‘HEllo‘

v1 = t1.partition(‘l‘)

print(v1)
输出;
(‘HE‘, ‘l‘, ‘lo‘)

 

 

 

  • replace:替换

 

t1 = ‘HEllo‘

v1 = t1.replace(‘l‘, ‘a‘)

print(v1)
输出:
HEaao

 

 

 

  • rfind:从右侧开始查找,返回索引

 

t1 = ‘HEllo‘

v1 = t1.rfind(‘l‘)

print(v1)
输出:
3

 

 

 

  • rindex:从右侧开始查找,返回索引

 


t1 = ‘HEllo‘

v1 = t1.rindex(‘l‘)

print(v1)
输出:
3

 

 

  • rjust:右侧对齐,左侧填充

 

t1 = ‘hello‘
t2 = ‘‘

v1 = t1.rjust(20,‘*‘)

print(v1)
输出:
***************hello

 

 

 

  • rpartition:拆分,从右侧开始查找

 

t1 = ‘HEllo‘

v1 = t1.rpartition(‘l‘)

print(v1)
输出:
(‘HEl‘, ‘l‘, ‘o‘)

 

 

 

  • rsplit:分割,默认以空格。从右侧开始,不显示count,表示全部

= "this is string example....wow!!!"

print (S.rsplit( ))

 

print (S.rsplit(‘i‘,1))

 

print (S.rsplit(‘w‘))
输出:

[‘this‘, ‘is‘, ‘string‘, ‘example....wow!!!‘]
[‘this is str‘, ‘ng example....wow!!!‘]
[‘this is string example....‘, ‘o‘, ‘!!!‘]

 

 

  • rstrip:去除右侧字符,不指定时,去除空格

 

t1 = ‘   HEllo   ‘

v1 = t1.rstrip()

print(v1)
输出:
   HEllo

t1 = ‘HEllo‘

v1 = t1.rstrip(‘o‘)

print(v1)
输出:
HEll

 

 

  • split:分割,默认以空格。从左侧开始,不显示count,表示全部

 

S = "this is string example....wow!!!"
print (S.split( ))
print (S.split(‘i‘,1))
print (S.split(‘w‘))
输出:

[‘this‘, ‘is‘, ‘string‘, ‘example....wow!!!‘]
[‘th‘, ‘s is string example....wow!!!‘]
[‘this is string example....‘, ‘o‘, ‘!!!‘]

 

 

  • splitlines:  在输出结果里是否去掉换行符(‘ ‘, ‘ ‘, ‘),默认为 False,不包含换行符,如果为 True,则保留换行符。

 

t =  ‘ab c

de fg
kl
‘

v1 = t.splitlines()
v2 = t.splitlines(True)

print(v1)
print(v2)
输出:

[‘ab c‘, ‘‘, ‘de fg‘, ‘kl‘]
[‘ab c ‘, ‘ ‘, ‘de fg ‘, ‘kl ‘]

 

 

 

  • startswith:以xxx开头

 

t1 = ‘HEllo‘

v1 = t1.startswith(‘h‘)
v2 = t1.startswith(‘H‘)

print(v1)
print(v2)
输出;

False
True

 

 

 

  • strip:去除两边的空格

 

t =  ‘  hello  ‘

v = t.strip()

print(v)
输出:
hello

 

 

  • swapcase:大写变小写,小写变大写

 

t =  ‘hEllO‘

v = t.swapcase()

print(v)
输出:
HeLLo

 

 

  • title:标题话,首字母大写

 

t =  ‘hello, every one‘

v = t.title()

print(v)
输出:
Hello, Every One

 

 

  • upper:转换成大写

 

t =  ‘hello‘

v = t.upper()

print(v)
输出:
HELLO

 

 

  • zfill:字符串靠右,左侧用0填充

 

str = "this is string example from runoob....wow!!!"
print ("str.zfill : ",str.zfill(40))
print ("str.zfill : ",str.zfill(50))
输出:

str.zfill : this is string example from runoob....wow!!!
str.zfill : 000000this is string example from runoob....wow!!!

 

 

 

 

 

 




































































































































































































































































































































































以上是关于Python3 字符串的主要内容,如果未能解决你的问题,请参考以下文章

scrapy按顺序启动多个爬虫代码片段(python3)

python常用代码片段总结

学习 PyQt5。在我的代码片段中找不到错误 [关闭]

21个常用代码片段

片段(Java) | 机试题+算法思路+考点+代码解析 2023

PHP 代码片段