美文网首页
Python-1-str

Python-1-str

作者: 态度哥 | 来源:发表于2019-12-20 10:27 被阅读0次

str list 切片

先说切片,因为str和list中切片都是一样的

例子 描述 其他
name[n:m] 切片是不包含后面那个元素的值(顾头不顾尾) n取到m-1
name[:m] 如果切片前面一个值缺省的话,从开头开始取
name[n:] 如果切片后面的值缺省的话,取到末尾
name[:] 如果全部缺省,取全部
name[n:m:s] s:步长 隔多少个元素取一次 步长是正数,从左往右取;步长是负数,从右往左取
name[::-1]) 把字符串和list倒叙

str

方法 描述 例子 备注
capitalize 首字母大写 str.capitalize() ->str
count 从一个范围内的统计某str出现次数 str.count('w',0, 6]) -> int w在索引0~6之间出现的次数
encode 编码 .encode('utf-8') ->bytes 以encoding指定编码格式编码,如果出错默认报一个ValueError,除非errors指定的是 ignore或replace
decode 解码 str.decode('utf-8') ->str
upper 字符串大写 str.upper() ->str
lower 字符串小写 str.lower()->str
split 字符串分割 str.split(',') -> list of strings 以括号中的字符分割字符串为list或strings
join 字符串合并 str = ','.join(['al', 'al34', '83']) ->str 参照join 字符串合并代码
replace 字符串替换 str.replace('北京','上海',1) ->str 把北京替换成上海,只替换第一个,把1去掉就替换所有
strip 字符串移除两边空白 str.strip() ;str.strip('>');str.strip('hello') ->str 括号中为空移除字符串两边的空白;有字符就移除两边的字符;多个字符就一个个的挨个移除
startswith 判断字符串的开始 str.startswith('2019-9-10 17:02') ->bool
endswith 判断字符串的结束 str.endswith('ing') ->bool
isdigit 判断字符串是不是全数字 str.isdigit() ->bool
isalpha 至少一个字符,且都是字母才返回True str.isalpha() ->bool
isalnum 至少一个字符,且都是字母或数字才返回True str.isalnum() -> bool
直接if 判断字符串是否为空 if str: ->bool 直接判断定义的字符串变量得到字符串是否为空
len 字符串的长度 len(str) ->int
in 字符串是否包含 # str = '菠萝蜜苹果香蕉' # print('香蕉' in s) 香蕉是否包含在str中(list也适用)

join 字符串合并


 #对序列进行操作(分别使用' '与':'作为分隔符)
        >>> seq1 = ['hello','good','boy','doiido']
        >>> print ' '.join(seq1)
        hello good boy doiido
        >>> print ':'.join(seq1)
        hello:good:boy:doiido


        #对字符串进行操作

        >>> seq2 = "hello good boy doiido"
        >>> print ':'.join(seq2)
        h:e:l:l:o: :g:o:o:d: :b:o:y: :d:o:i:i:d:o


        #对元组进行操作

        >>> seq3 = ('hello','good','boy','doiido')
        >>> print ':'.join(seq3)
        hello:good:boy:doiido


        #对字典进行操作

        >>> seq4 = {'hello':1,'good':2,'boy':3,'doiido':4}
        >>> print ':'.join(seq4)
        boy:good:doiido:hello


        #合并目录

        >>> import os
        >>> os.path.join('/hello/','good/boy/','doiido')
        '/hello/good/boy/doiido'


        S.join(iterable) -> str

字符串是否包含某个子字符串

if str1 in str2:

  包含的话,True

if str1.find(str2)>=0:

  包含的话,返回第一次出现的位置,没有的话为负数

去除字符串中不想要的字符

#去除两边的空格
s.strip()
#删除右边空字符
s.rstrip()
#删除左边空支付
s.lstrip()
#删除两边的的  ’-‘ 号
s.strip('-')

删除单个固定位置字符: 切片 + 拼接

s = 'abc:567'
# 字符串拼接方式去除冒号
new_s = s[:3] + s[4:]    
print(new_s)
>>> abc567

删除任意位置字符同时删除多种不同字符:replace(), re.sub()

# 去除字符串中相同的字符
s = '\tabc\t123\tisk'  #直接替换\t为空
print(s.replace('\t', ' '))


import re
# 去除\r\n\t字符
s = '\r\nabc\t123\nxyz'
print(re.sub('[\r\n\t]', '', s))

同时删除多种不同字符:translate() py3中为str.maketrans()做映射

s = 'abc123xyz'
# a _> x, b_> y, c_> z,字符映射加密
print(str.maketrans('abcxyz', 'xyzabc'))
# translate把其转换成字符串
print(s.translate(str.maketrans('abcxyz', 'xyzabc')))

去掉unicode字符中音调

import sys
import unicodedata
s = "Zhào Qián Sūn Lǐ Zhōu Wú Zhèng Wáng"
remap = {
    # ord返回ascii值
    ord('\t'): '',
    ord('\f'): '',
    ord('\r'): None
    }
# 去除\t, \f, \r
a = s.translate(remap)
'''
  通过使用dict.fromkeys() 方法构造一个字典,每个Unicode 和音符作为键,对于的值全部为None
  然后使用unicodedata.normalize() 将原始输入标准化为分解形式字符
  sys.maxunicode : 给出最大Unicode代码点的值的整数,即1114111(十六进制的0x10FFFF)。
  unicodedata.combining:将分配给字符chr的规范组合类作为整数返回。 如果未定义组合类,则返回0。
'''
cmb_chrs = dict.fromkeys(c for c in range(sys.maxunicode) if unicodedata.combining(chr(c))) #此部分建议拆分开来理解
b = unicodedata.normalize('NFD', a)
'''
   调用translate 函数删除所有重音符
'''
print(b.translate(cmb_chrs))

just,向右对其,在左边补空格

s = "123".rjust(5)
print(s)
# # assert s == " 123"

ljust向左对其,在右边补空格

s1 = "123".ljust(5)
print(s1)
# # assert s == "123 "

center让字符串居中,在左右补空格

s2 = "123".center(5)
print(s2)
# assert s == " 123 "

相关文章

  • Python-1-str

    str list 切片 先说切片,因为str和list中切片都是一样的 例子描述其他name[n:m]切片是不包含...

网友评论

      本文标题:Python-1-str

      本文链接:https://www.haomeiwen.com/subject/jnpbnctx.html