首页 > 编程语言 > 详细

python字符串

时间:2020-11-10 10:00:47      阅读:26      评论:0      收藏:0      [点我收藏+]

1、str() 可以将其他 Python 数据类型转换为字符串:
-->> str(98.6)
‘98.6‘
2、\转义符号 例如:\n是换行
3、[]为切片 [start:end:step][开始:结束:间隔]
4、len()获得长度
5、split()分割
-->> todos = ‘get gloves,get mask,give cat vitamins,call ambulance‘
-->> todos.split(‘,‘)
[‘get gloves‘, ‘get mask‘, ‘give cat vitamins‘, ‘call ambulance‘]
6、join()合并
-->> crypto_list = [‘Yeti‘, ‘Bigfoot‘, ‘Loch Ness Monster‘]
-->> crypto_string = ‘, ‘.join(crypto_list)
-->> print(‘Found and signing book deals:‘, crypto_string)
Found and signing book deals: Yeti, Bigfoot, Loch Ness Monster
7、
-->>poem = ‘‘‘All that doth flow we cannot liquid name
Or else would fire and water be the same;
But that is liquid which is moist and wet
Fire that property can never get.
Then ‘tis not cold that doth the fire put out
But ‘tis the wet that makes it die, no doubt.‘‘‘
判断开头,这首诗是不是以 All 开头呢?
-->> poem.startswith(‘All‘)
True
判断结尾,它是否以 That‘s all, folks!? 结尾?
-->> poem.endswith(‘That‘s all, folks!‘)
False
查询初始位置,查一查诗中第一次出现单词 the 的位置(偏移量):
-->> word = ‘the‘
-->> poem.find(word)
73
查询结束位置,以及最后一次出现 the 的偏移量 :
-->> poem.rfind(word)
214
查询次数,the 在这首诗中出现了多少次?
-->> poem.count(word)
3
判断是否为字符数字,诗中出现的所有字符都是字母或数字吗?
-->> poem.isalnum()
False
并非如此,诗中还包括标点符号。
8、大小写
-->> setup = ‘a duck goes into a bar...‘
将字符串收尾的 . 都删除掉:
-->> setup.strip(‘.‘)
‘a duck goes into a bar‘
让字符串首字母变成大写:
-->> setup.capitalize()
‘A duck goes into a bar...‘
让所有单词的开头字母变成大写:
-->> setup.title()
‘A Duck Goes Into A Bar...‘
让所有字母都变成大写:
-->> setup.upper()
‘A DUCK GOES INTO A BAR...‘
将所有字母转换成小写:
-->> setup.lower()
‘a duck goes into a bar...‘
将所有字母的大小写转换:
-->> setup.swapcase()
‘a DUCK GOES INTO A BAR...‘
再来看看与格式排版相关的函数。这里,我们假设例子中的字符串被排版在指定长度(这
里是 30 个字符)的空间里。
在 30 个字符位居中:
-->> setup.center(30)
‘ a duck goes into a bar... ‘
左对齐:
-->> setup.ljust(30)
‘a duck goes into a bar... ‘
右对齐:
-->> setup.rjust(30)
‘ a duck goes into a bar...‘
9、replace()替换
-->> setup = ‘a duck goes into a bar...‘
-->> setup.replace(‘duck‘, ‘marmoset‘)
‘a marmoset goes into a bar...‘
修改最多 100 处:
-->> setup.replace(‘a ‘, ‘a famous ‘, 100)
‘a famous duck goes into a famous bar...‘

python字符串

原文:https://www.cnblogs.com/zozb/p/13951761.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!