python数据处理技巧一

python–字符串处理技巧

1、+操作

对字符串组合

a="jupyter"
b="notebook"
print(a+b)

---result---
jupyternotebook

2、*操作

重复字符串个数

a="jupyter notebook\n"
print(a*5)

---result---
jupyter notebook
jupyter notebook
jupyter notebook
jupyter notebook
jupyter notebook

3、in操作

用于判断某个字符是否在指定字符串中,与pandas的数据筛选组合使用,快速选出对应数据

l="jupyter notebook"
print(l in the "best tool to learn python is jupyter notebook")

---result---
True

4、[]和[:]通过索引获取字符串中的字符

s='jupyter notebook'
s[7]
s[0:7:2] #索引位置为0到6,每隔一个进行取数(步长为2)
---result---
' '

5、字符串内置方法

  • s.capitalize():把字符串第一个字符大写,其他的字符串都小写
        
    s='jupyterNotebook'
    s.capitalize()
    ---result---
    'Jupyternotebook'
    
  • s.lower():字符串所有大写字符变为小写
    
    s = "jupyterNotebook"
    s.lower()
    ---result---
    'jupyternotebook'
    
  • s.upper():字符串小写字母变大写
    
    s = "jupyterNotebook"
    s.upper()
    ---result---
    'JUPYTERNOTEBOOK'
    
  • s.title():所有的单词都以大写开始,其余字母小写
    
    s='jupyter notebook'
    s.title()
    ---result---
    'Jupyter Notebook'
    
  • s.startswith(str):检查字符串是否以str开头
    s.startswith('jup')
    ---result---
    True
    
  • s.endswith(str):检查字符串是否以str结尾
    s.endswith('ook')
    ---result---
    True
    

    数据选择过程中,与pandas结合,实现高效取数

6、字符串与列表之间的转换

  • 将列表转换为字符串,可以使用" ".join()
list_1=['jupyter','notebook','bin','python']
str_1=" ".join(list_1)
print(str_1)
---result---
jupyter notebook bin python
  • 字符串变为列表,用s.split()
str_2='jupyter notebook bin python'
list_2=str_2.split('') # 空格为分隔符
print(list_2)
---result---
['jupyter notebook bin python']
str.split(sep,maxsplit)
sep:用于指定分隔符,可以包含多个字符 (例如 '1<>2<>3'.split('<>') 将返回 ['1', '2', '3'])。此参数默认为 None,表示所有空字符,包括空格、换行符 \n、制表符 \t 等

maxsplit:可选参数,用于指定分割的次数(因此,列表最多会有 maxsplit+1 个元素),如果不指定或者指定为 -1,则表示分割次数没有限制。

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值