Python字符串

字符串引号介绍
name  = "Changsha" #双引号
age = "5000" #只要加双引号就是字符串
age_1 = 5000 #不加,整型
msg = """ I'm in Changsga """ #三双引号
msg_1 = ''' I'm in Hengyang ''' #三单引号
hometowm = 'changsha' #单引号
print(type(name),type(age),type(age_1),type(msg),type(msg_1),type(hometowm))
<class 'str'> <class 'str'> <class 'int'> <class 'str'> <class 'str'> <class 'str'>
##########012345678901234567890123456789
>>> a = "Life is short, I use python"
>>> len(a)
27
>>> #索引
...
>>> a[0]
'L'
>>> a[15]
'I'
>>> a[-1]
'n'
>>> a[-6]
'p'
>>> #切片
...
>>> 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'
>>>
大小写转换
  • 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'
>>>
字符串格式输出对齐
  • str.center()
  • str.ljust()
  • str.rjust()
  • str.zfill()
>>> 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.rjust(35,'*') # 返回一个原字符串右对齐,并使用空格填充至长度 width 的新字符串
'********Life is short, I use python'
>>> a.zfill(35) # 返回长度为 width 的字符串,原字符串 string 右对齐,前面填充0,只有一个参数
'00000000Life is short, I use python'
>>>

删除指定字符

  • 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'
计数

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

>>> a = "Life is short, I use python"
>>> a.count("i") # 返回 str 在 string 里面出现的次数
2
>>> a.count("i",4,8) # 在索引值为[4,8)的范围内 str 出现的次数
1
字符串搜索定位与替换
  • 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) # 查找元素在指定索引范围内的索引
19
>>> a.index('w') # 找不到值返回-1
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') # 查找一段元素并转换为其他元素
'Life is short, You need python'
>>> a.replace('t','T') # 查找单个元素并转换为大写
'Life is shorT, I use pyThon'
>>> a.replace('t','T',1) # 查找索引第一个元素并转化为大写T
'Life is shorT, I use python'
字符串条件判断
  • 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

制表符转化

str.expandtabs()

>>> a = "L\tife is short, I use python"
>>> a.expandtabs() # 默认将制表符转化为8个空格
'L       ife is short, I use python'
>>> a.expandtabs(4) # 加上参数,将制表符转化为对应个数的空格
'L   ife is short, I use python'
>>>
str.expandtabs();制表符转化
  • str.expandtabs([x]); # 有参数时,将制表符转化为指定个数的空格。
>>> b
'我love China\t 制表符'
>>> b.expandtabs()
'我love China      制表符'
>>> b.expandtabs(2)
'我love China  制表符'
ASCll码个字符之间的转化
  • chr(x); # 将数字转换为 '字符‘
  • ord©; # 将字符转换为 数字
>>> chr(97)
'a'
>>> ord('a')
97
字符串分割变换
  • join() 将指定字符插入到元素之间
  • split()以指定字符分隔序列且去除该字符
  • partition()以指定字符分隔序列且包含该字符
>>> str = "learn string"
>>> '_'.join(str)
'l_e_a_r_n_ _s_t_r_i_n_g'
>>> '+'.join(str)
'l+e+a+r+n+ +s+t+r+i+n+g'
>>> li = ["learn","string"]
>>> '_'.join(li)
'learn_string'
>>> 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')
>>>
>>> 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.ascii_lowercase
'abcdefghijklmnopqrstuvwxyz'
>>> string.ascii_uppercase
'ABCDEFGHIJKLMNOPQRSTUVWXYZ'
>>> string.capwords('hUNAN yingxiao college')
'Hunan Yingxiao College'

"%"是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 hex is %X") %(a,a))
15 to hex is F
>>> "%x" % 15
'f'
>>> "%f" % 15
'15.000000'
>>> "%e" % 15000
'1.500000e+04'
>>> "%d" % 100
'100'
>>> "%d%%" % 100
'100%'

可以用如下的方式,对格式进行进一步的控制:

%(name)[width].[precision]typecode

(name)为命名

flags可以有+,-,’ ‘或0。+表示右对齐。-表示左对齐。’ '为一个空格,表示在正数的左侧填充一个空格,从而与负数对齐。0表示使用0填充。

width表示显示宽度

precision表示小数点后精度

>>> "His name is %s\n his age is %d" % ("Tom", 18)
>>> 'His name is Tom\n his age is 18'
>>> print("His name is %s\n his age is %d" % ("Tom", 18))
>>> His name is Tom
>>>  his age is 18
>>> print(r"His name is %s\n his age is %d" % ("Tom", 18))
>>> His name is Tom\n his age is 18
>>> 
  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值