python入门:有关字符串的操作代码总结

# 作者:王杰安 暨南大学 
# string
def report_code(oper):
    result = eval(oper)
    print('{} = {}'.format(oper, result))
def report_variable(str):
    print('{} = {}'.format(str, eval(str)))
print('不同类型的引号')
print('string_1')
print("'string_1': string_2") #包含单引号
print('''首行输出:string_3
接着上面换行:string_3''')# 可以换行
print("""首行输出:string_4  
接着上面换行:string_4""") # 可以换行
#----------------------------------------#
print()
# 字符串运算符
report_code("'I' + ' LOVE' + ' YOU'")
report_code("'I'*3")
report_code("'I' in 'I Love U'")
report_code("'a' in 'I Love U'")
# 索引和切片
print()
word = 'I want play with you'
report_code('word[:]')
report_code('word[0]')
report_code('word[-1]')
report_code('word[1:]')
report_code('word[:-3]')
report_code('word[2:6]')
report_code('word[-10:-3]')
report_code('word[2:-4]')
print()
# 步长必须大于0
print()
report_code('word[:6:1]')
report_code('word[:6:2]')
report_code('word[::2]')
report_code('word[::-1]')# 反向排序
report_code('word[::-2]')
# 字符串处理函数
print()
x = 'I Love U'
report_code('len(x)')
report_code('str(123)')
report_code("chr(9990)")
report_code("ord('a')")
report_code('hex(2)')
report_code('oct(10)')
# 内置的字符串处理方法
print()
# 字符串处理方法
print('字符串查找方法')
word = 'I Love u Love I u'
print(word)
# 不存在返回-1
report_code("word.find('Love')")
report_code("word.rfind('u')")
# 不存在抛出异常
report_code("word.index('Love')")
report_code("word.rindex('I')")
report_code("word.count('I')")
report_code("word.count('Love')")
#======================================#
print()
print('字符串分类方法')
a = 'bird,fish:monkey:fish,tiger,rabbit'
print(a)
# 从前开始分割
report_code("a.split(',')")
report_code("a.split(',',1)")# 只分隔第一个
# 从后开始分隔
report_code("a.rsplit(',',1)")# 只分隔最后一个
report_code("a.rsplit(',',2)")
# 左右分割 partition返回元组
report_code("a.partition(':')")
report_code("a.rpartition(':')")
#================================================#
print()
print('字符串连接方法')
word = ['I', 'Love', 'U']
report_code("'--'.join(word)")
report_code("' '.join(word)")
report_code("':'.join(word)")
#================================================#
print()
print('大小写转化')
word = 'i LoVe U but I waNt PlaY !'
report_code('word.lower()')
report_code('word.upper()')
report_code('word.capitalize()') # 首字母大写,其他小写
report_code('word.title()') # 每个单词首字母大写,其他小写
report_code('word.swapcase()')# 大小写交换
#================================================#
print()
print('字符串替换')
word = '你是我的小呀小苹果'
report_code("word.replace('小', 'samll')")
#================================================#
print()
print('字符串清洗')
word = '   abc    '; strs = '===abc===='
report_variable('word')
report_variable('strs')
report_code("word.strip()")
report_code("word.rstrip()")
report_code("word.lstrip()")
report_code("strs.strip('=')")
#================================================#
print()
print('字符串开始结束判断')
word = 'I Love U'
report_variable('word')
report_code("word.startswith('I')")
report_code("word.endswith('U')")
#================================================#
print()
print('字符串类型方法')
report_code("'years'.islower()")
report_code("'YEARS'.isupper()")
report_code("'123'.isdigit()")
report_code("'abc'.isalpha()")
report_code("'123abc'.isalnum()")
#================================================#
print()
print('字符串排版方法')
word = 'I am handsome'
report_code("word.center(30, '=')")
report_code("word.ljust(30, '-')")
report_code("word.rjust(30, '?')")
report_code("word.zfill(30)")
#================================================#
print()
print('format格式化')
report_code("'{} is {}'.format('A', 'B')")
report_code("'{1} is {0}'.format('A', 'B')")
report_code("'{:^20}'.format('WJA')")
report_code("'{:-^20}'.format('WJA')")
report_code("'{:=<30}'.format('WJA')")
report_code("'{:.2f}'.format(13.1234)")
report_code("'{:.3f}'.format(13.1234)")
report_code("'{:5d}'.format(13)")
report_code("'{:x>5d}'.format(13)")
report_code("'{:x^5d}'.format(13)")
#================================================#
print()
print('强制转化')
report_code("int(2.6)")
report_code("float(2)")

输出结果

不同类型的引号
string_1
'string_1': string_2
首行输出:string_3
接着上面换行:string_3
首行输出:string_4  
接着上面换行:string_4

'I' + ' LOVE' + ' YOU' = I LOVE YOU
'I'*3 = III
'I' in 'I Love U' = True
'a' in 'I Love U' = False

word[:] = I want play with you
word[0] = I
word[-1] = u
word[1:] =  want play with you
word[:-3] = I want play with 
word[2:6] = want
word[-10:-3] = y with 
word[2:-4] = want play with


word[:6:1] = I want
word[:6:2] = Iwn
word[::2] = Iwn lywt o
word[::-1] = uoy htiw yalp tnaw I
word[::-2] = uyhi apta 

len(x) = 8
str(123) = 123
chr(9990) =ord('a') = 97
hex(2) = 0x2
oct(10) = 0o12

字符串查找方法
I Love u Love I u
word.find('Love') = 2
word.rfind('u') = 16
word.index('Love') = 2
word.rindex('I') = 14
word.count('I') = 2
word.count('Love') = 2

字符串分类方法
bird,fish:monkey:fish,tiger,rabbit
a.split(',') = ['bird', 'fish:monkey:fish', 'tiger', 'rabbit']
a.split(',',1) = ['bird', 'fish:monkey:fish,tiger,rabbit']
a.rsplit(',',1) = ['bird,fish:monkey:fish,tiger', 'rabbit']
a.rsplit(',',2) = ['bird,fish:monkey:fish', 'tiger', 'rabbit']
a.partition(':') = ('bird,fish', ':', 'monkey:fish,tiger,rabbit')
a.rpartition(':') = ('bird,fish:monkey', ':', 'fish,tiger,rabbit')

字符串连接方法
'--'.join(word) = I--Love--U
' '.join(word) = I Love U
':'.join(word) = I:Love:U

大小写转化
word.lower() = i love u but i want play !
word.upper() = I LOVE U BUT I WANT PLAY !
word.capitalize() = I love u but i want play !
word.title() = I Love U But I Want Play !
word.swapcase() = I lOvE u BUT i WAnT pLAy !

字符串替换
word.replace('小', 'samll') = 你是我的samll呀samll苹果

字符串清洗
word =    abc    
strs = ===abc====
word.strip() = abc
word.rstrip() =    abc
word.lstrip() = abc    
strs.strip('=') = abc

字符串开始结束判断
word = I Love U
word.startswith('I') = True
word.endswith('U') = True

字符串类型方法
'years'.islower() = True
'YEARS'.isupper() = True
'123'.isdigit() = True
'abc'.isalpha() = True
'123abc'.isalnum() = True

字符串排版方法
word.center(30, '=') = ========I am handsome=========
word.ljust(30, '-') = I am handsome-----------------
word.rjust(30, '?') = ?????????????????I am handsome
word.zfill(30) = 00000000000000000I am handsome

format格式化
'{} is {}'.format('A', 'B') = A is B
'{1} is {0}'.format('A', 'B') = B is A
'{:^20}'.format('WJA') =         WJA         
'{:-^20}'.format('WJA') = --------WJA---------
'{:=<30}'.format('WJA') = WJA===========================
'{:.2f}'.format(13.1234) = 13.12
'{:.3f}'.format(13.1234) = 13.123
'{:5d}'.format(13) =    13
'{:x>5d}'.format(13) = xxx13
'{:x^5d}'.format(13) = x13xx

强制转化
int(2.6) = 2
float(2) = 2.0

好物分享
python: 数据科学代码速查表(强烈推荐!)
入门总结:
python入门:有关字符串的操作代码总结
python入门:有关math包以及内置函数的数值操作代码总结
Python练习:
python:第二章 字符串和数值程序作业
python:第三章 程序流程控制作业
python:第三章 程序流程控制作业2
python:第四章 列表与元组作业
python:第四章 列表与元组作业2

发布了20 篇原创文章 · 获赞 3 · 访问量 1500

猜你喜欢

转载自blog.csdn.net/qq_42830966/article/details/104817977