python字符串基本操作

访问: 循环, 索引, 切片

>>> s = 'abcdefg'
>>> s[-2]
'f'
>>> s[0::2]
'aceg'
>>> s[0::]
'abcdefg'
>>> s[::-1]
'gfedcba'

格式化访问 format

用{ }占位, 用format( )填入

print("I {} excellent!".format("am"))
url = 'https://www.{}.net/'
name = 'csdn'
whole_url = url.format(name)
print(url,"\n", whole_url)
'''
输出结果:
I am excellent!
https://www.{}.net/ 
 https://www.csdn.net/	
'''

拼接 +

a = 'I am'
b = 'a boy.'
c = a + ' ' + b
>>> c
'I am a boy.'

替换和查找 find, index, replace

find 返回找到元素的第一个位置的索引值, 找不到返回-1
index 找不到抛出异常

>>> url = 'https://www.{}.net/'.format('csdn')
>>> url.find('csdn')
12
>>> url.index('csdn')
12
>>> url.find('csadn')
-1
>>> url.index('csadn')
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
ValueError: substring not found

>>> new_url = url.replace('csdn', 'cs')
>>> new_url
'https://www.cs.net/'
>>> url
'https://www.csdn.net/'

统计 len, count

count 统计某个字符(串)在字符串中出现的次数

>>> url = 'https://www.{}.net/'.format('csdn')
>>>len(url)
21
>>> url.count('w')
3
>>> url.count('ww')
1
>>> url.count('www')
1

大小写 title, upper, lower

>>> str = 'i am a boY.'
>>> str.title()
'I Am A Boy.'
>>> str.upper()
'I AM A BOY.'
>>> str.lower()
'i am a boy.'

去空格和换行符 strip

strip() 方法用于移除字符串头尾指定的字符(默认为空格或换行符)或字符序列。
注意:该方法只能删除开头或是结尾的字符,不能删除中间部分的字符。

>>> str = ' i am a boY.\n'
>>> str.strip()
'i am a boY.'
>>> str.lstrip()
'i am a boY.\n'
>>> str.rstrip()
' i am a boY.'

拆分split

>>> str = ' i am a boY.\n'
>>> str.split(' ')
['', 'i', 'am', 'a', 'boY.\n']

判断类型isalpha, isdigit, isalnum, isidentifier

isidentifier:判断是否是标识符

编码encode与解码decode

https://www.cnblogs.com/shine-lee/p/4504559.html

dir列出所有可操作方法

>>>str='abc'
>>> dir(str)
['__add__', '__class__', '__contains__', '__delattr__', '__dir__', '__doc__', '__eq__', '__format__', '__ge__', '__getattribute__', '__getitem__', '__getnewargs__', '__gt__', '__hash__', '__init__', '__init_subclass__', '__iter__', '__le__', '__len__', '__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__', '__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__', '__sizeof__', '__str__', '__subclasshook__', 'capitalize', 'casefold', 'center', 'count', 'encode', 'endswith', 'expandtabs', 'find', 'format', 'format_map', 'index', 'isalnum', 'isalpha', 'isdecimal', 'isdigit', 'isidentifier', 'islower', 'isnumeric', 'isprintable', 'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip', 'maketrans', 'partition', 'replace', 'rfind', 'rindex', 'rjust', 'rpartition', 'rsplit', 'rstrip', 'split', 'splitlines', 'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值