Python 字符串常见操作

切片操作(slice)可以从一个字符串中获取子字符串(字符串的一部分)。我们使用一对方括号、起始偏移量start、终止偏移量end 以及可选的步长step 来定义一个分片。

格式: [start:end:step]

• [:] 提取从开头(默认位置0)到结尾(默认位置-1)的整个字符串
• [start:] 从start 提取到结尾
• [:end] 从开头提取到end - 1
• [start:end] 从start 提取到end - 1
• [start:end:step] 从start 提取到end - 1,每step 个字符提取一个
• 左侧第一个字符的位置/偏移量为0,右侧最后一个字符的位置/偏移量为-1

 

几个特别的examples 如下:

提取最后N个字符:

>>> letter = 'abcdefghijklmnopqrstuvwxyz'
>>> letter[-3:]
'xyz'

从开头到结尾,step为N:

>>> letter[::5]
'afkpuz'

将字符串倒转(reverse), 通过设置步长为负数:

>>> letter[::-1]
'zyxwvutsrqponmlkjihgfedcba'

反向索引:S="Spam"

S="Spam"
print(S[-1])
print(S[-2])

#下列两个写法等效
S[-1]
S[len(S)-1]

从最后一个开始,从右边开始计算

# P87 第四章
import math
import random

# 数字
print("length of 2**1000000",len(str(2**1000000)))
# math 模块包含很多数学工具
print("pi:",math.pi)
print("sqrt of 96", math.sqrt(96))
# random模块
print("random:",random.random())
print("choice",random.choice([2,3,4,5,6,7]))

# 字符串
# 序列的操作
S = "Spam"
len(S)
S[2]
for x in S:
    print(x)
print(S[:-2]) # 输出Sp
# 查找
print(S.find('a'))
print(S.find('k')) # 找不到返回-1
# 替换
print(S.replace('pa','XYZ'))
print(S) # 不会改变原有字符串,而是创建新的字符串作为结果

line='aa,bbb,cc cc,ddd\n'
print(line.split(','))  # 以,分割
print(line.upper())
print(line.rstrip())    # 去掉右侧空白

# 帮助
print(dir(S))
print(help(S.replace))

msg=""" aaaaaaaaaaaaaa
bbb'''bbbbbbbb""bbbbbbbbbb'bbbb
ccccccccccccccccc"""
print(msg)
# 模式匹配
import re
match = re.match('Hello[\t]*(.*)world','Hello    Python world')
print(match.group())

match = re.match('/(.*)/(.*)/(.*)','/usr/home/lumberjack')
print(match.group())
Python 3.7.0 (v3.7.0:1bf9cc5093, Jun 27 2018, 04:59:51) [MSC v.1914 64 bit (AMD64)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> 
==================== RESTART: F:\PyCode\Day2对象类型\对象类型.py ====================
length of 2**1000000 301030
pi: 3.141592653589793
sqrt of 96 9.797958971132712
random: 0.8443446287680388
choice 3
S
p
a
m
Sp
2
-1
SXYZm
Spam
['aa', 'bbb', 'cc cc', 'ddd\n']
AA,BBB,CC CC,DDD

aa,bbb,cc cc,ddd
['__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', 'isascii', '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']
Help on built-in function replace:

replace(old, new, count=-1, /) method of builtins.str instance
    Return a copy with all occurrences of substring old replaced by new.
    
      count
        Maximum number of occurrences to replace.
        -1 (the default value) means replace all occurrences.
    
    If the optional argument count is given, only the first count occurrences are
    replaced.

None
 aaaaaaaaaaaaaa
bbb'''bbbbbbbb""bbbbbbbbbb'bbbb
ccccccccccccccccc
>>> 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值