Python学习笔记—字符串

一、字符串的连接和复制

字符串间的连接用“+”号,不同数据类型之间不能直接连接。

>>>'Yvette' + 'zheng'
'Yvettezheng'

>>>'Yvette' + 1
Traceback (most recent call last):
  File "<ipython-input-2-c795e6c59527>", line 1, in <module>
    'Yvette' + 1
TypeError: must be str, not int

 

 

二、字符串切片

字符串切片string[0:2]可以任意选取内容,也可以指定位置进行替换。

>>>'Hello World'[6:]
'World'

>>>'Hello World'[:6] + 'Yvette'
'Hello Yvette'

 

三、原始字符串类型

字符串前面添加r,表示字符串按字面来,避免转义。

>>>print('Hello\nWorld')
Hello
World

>>>print(r'Hello\nWorld')
Hello\nWorld

 

四、内建函数

1、格式化字符串string.format()

例子   {0:^10}\t{1:{3}^10}\t{2:^10}.format("排名","学校名称","总分", chr(12288)) 

参考连接:http://www.runoob.com/python/att-string-format.html

https://docs.python.org/3/library/string.html#grammar-token-conversion

2、_repr_和_str_的区别

3、删除首尾字符

>>>spam = '  Hello World  ' 
>>>spam.strip()
'Hello World'

>>>spam.lstrip()
'Hello World  '

>>>spam.rstrip()
'  Hello World'

>>>spam = 'SpamapmSBaconSpamEggspamSpam'
>>>spam.strip('ampS') #a、m、p、S的顺序不重要
'BaconSpamEggs'

 

4、分割sep.split()和连接sep.join()

>>>'.'.join(['My','name','is','Yvette'])
'My.name.is.Yvette'

>>>'My name is Yvette'.split()
['My', 'name', 'is', 'Yvette']

 

5、文本对齐

>>>'Hello'.rjust(10)
'     Hello'

>>>'Hello'.ljust(10)
'Hello     '

>>>'Hello'.center(20,'=')
'=======Hello========'

打印表格式数据

def printPicnic(itemsDict,leftWidth,rightWidth):
    print('PICNIC ITEMS'.center(leftWidth+rightWidth, '-'))
    for k, v in itemsDict.items():
        print(k.ljust(leftWidth, '.') + str(v).rjust(rightWidth))
picnicItems = {'sandwiches': 4, 'apples': 12, 'cups': 4, 'cookies': 8000}
printPicnic(picnicItems, 20, 6)

-------PICNIC ITEMS-------
sandwiches..........     4
apples..............    12
cups................     4
cookies.............  8000

 

6、大小写转换

>>>spam = 'Hello World!'
>>>spam.upper() #全部变为大写
'HELLO WORLD!'

>>>spam.lower() #全部变为小写
'hello world!'

 

7.布尔值判断.isX方法

.isupper()返回True,如果字符串至少有一个字母,并且所有字母都是大写;

.islower()返回True,如果字符串至少有一个字母,并且所有字母都是小写;

.isalpha()返回True,如果字符串只包含字母,并且非空;

.isalnum()返回True,如果字符串只包含字母和数字,并且非空;

.isdecimal()返回True,如果字符串只包含数字,并且非空;

.isspace()返回True,如果字符串只包含空格、制表符和换行,并且非空;

.istitle()返回True,如果字符串仅包含以大写字母开头、后面都是小写字母的单词。

 

参考链接

 

 
 

 

 

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

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值