6-2、Python 数据类型-字符串

简介: 学习Python 数据类型-字符串。

Python字符串介绍:存储类型,python字符串类型的转换,字符串输入和输出,字符串的拼接、字符串下标,字符串切片,字符串常见操作,字符串格式化

存储方式


整型在内存中占一个字节,字符串不管中间有多少内容都要单独存储

类型的转换


Int将字符串转换成整型

Str将整型转换成字符串

>>> num = '100'
>>> type(num)
<class 'str'>
>>> int(num)   # 转换为int类型输出,并不是改变它的实际类型
100
>>> type(int(num))
<class 'int'>
>>> num
'100'
>>> num = 'abc' # 只有数字的字符串可以转换为整型
>>> int(num)
Traceback (most recent call last):
  File "<pyshell#8>", line 1, in <module>
    int(num)
ValueError: invalid literal for int() with base 10: 'abc'
>>> 
>>> num = 100
>>> type(num)
<class 'int'>
>>> str(num)
'100'
>>> num
100
>>> num = str(num) # 转换为字符串在赋值给num
>>> num
'100'
>>> 

字符串输入和输出

>>> name = 'jack'
>>> sex = '男'
>>> age = 18
>>> print("你的姓名是:%s"%name)
你的姓名是:jack
>>> print("性别:%s"%sex)
性别:男
>>> print("年龄:%d"%age)
年龄:18
>>> username = input("请输入用户名:")
请输入用户名:jack
>>> password = input("请输入密码:")
请输入密码:123456
>>> print("用户名: %s"%username)
用户名: jack
>>> print("密码:%s"%password)
密码:123456
>>> 

字符串拼接


1)字符串相加 2)字符串格式化

>>> a = 'ja'
>>> b = 'ck'
>>> c = a + b # 当+号两边是str字符串时,为拼接
>>> c
'jack'
>>> d =100
>>> e = 200
>>> f = d + e  # 当+号两边都是int数字时,为相加求和
>>> f
300
>>> g = '===%s==='%(a+b)
>>> g
'===jack==='
>>> 

字符串下标**


name = “abcdef”,如何取出c值?如何取出最后-一个值?

>>> name = 'abcdef'
>>> name[0]
'a'
>>> name[2]
'c'
>>> name[5]
'f'
>>> name[6]
Traceback (most recent call last):
  File "<pyshell#43>", line 1, in <module>
    name[6]
IndexError: string index out of range  # 字符串越界,只要超出了范围不管从左取还是从右取
>>> 
>>> len(name) # len 求字符串长度函数
6
>>> len(name)-1
5
>>> name[len(name)-1]
'f'
>>> name[-1] # -1 是从右往左取
'f'
>>> name[-2]
'e'
>>> name[-7]
Traceback (most recent call last):
  File "<pyshell#49>", line 1, in <module>
    name[-7]
IndexError: string index out of range
>>> 

字符串切片**(得到子字符串)


字符串是不可以修改的,所以对子字符串是只能读不能写


name =“abcdefABCDEF"如何取出ced值? name逆序输出,怎么办?

>>> name='abcdefABCDEF'
>>> name[2:5]  #第3个到第5个字符
'cde'
>>> name[2:]
'cdefABCDEF'
>>> name[2::2] # 起始位置: 终止位置: 步长:
'ceACE'
>>> name[::2]
'aceACE'
>>> name[1:10:2] # 起始位置: 终止位置: 步长:
'bdfBD'
>>> name[-1::-1]
'FEDCBAfedcba'
>>> name[::-1] # 步长控制字符串取的方向
'FEDCBAfedcba'
>>>  


字符串常见操作


1)find 查找

>>> mystr='hello world jack and tomjack'
>>> mystr.find('jack') # 查找当前第一次出现字符串的的位置
12
>>> mystr.rfind('jack') #查找当前最后一次出现字符串的位置
24
>>> mystr.find('jr')  # 查找不存在字符串的会返回一个:-1
-1
>>>

2)index

>>> mystr.index('jack')
12
>>> mystr.rindex('jack')
24
>>> mystr.index('jr') # index查找不存在的字符串 会报错
Traceback (most recent call last):
  File "<pyshell#29>", line 1, in <module>
    mystr.index('jr')
ValueError: substring not found
>>> 

3) replace 替换

>>> mystr='hello world jack and tomjack'
>>> mystr.replace('world','WORLD')
'hello WORLD jack and tomjack'
>>> mystr.replace('jack','JACK')
'hello world JACK and tomJACK'
>>> mystr.replace('jack','JACK',1) #参数1 替换一次
'hello world JACK and tomjack'
>>> mystr.replace('jack','JACK',2)
'hello world JACK and tomJACK'
>>> mystr.replace('jack','JACK',3) # 没有报错把前两个替换了
'hello world JACK and tomJACK'
>>> mystr=mystr.replace('jack','JACK',2)
>>> mystr
'hello world JACK and tomJACK'

4) split 分割成字符串列表

>>> mystr='hello world JACK and tomJACK'
>>> mystr.split(' ')
['hello', 'world', 'JACK', 'and', 'tomJACK']
>>> mystr.split('JACK')
['hello world ', ' and tom', '']
>>> 

5) startswith 返回一个布尔值

>>> mystr='hello world jack and tom'
>>> mystr
'hello world jack and tom'
>>> mystr.split(' ')
['hello', 'world', 'jack', 'and', 'tom']
>>> mystr.startswith('hello')
True
>>> mystr.startswith('helloa')
False
>>> 

6) endswith

>>> mystr='hello world jack and tom'
>>> mystr.endswith('tom')
True
>>> mystr.endswith('t')
False
>>> 

7 ) lower 将大写转换为小写

>>> name = 'JACK'
>>> name.lower()
'jack'
>>> 

8) upper 将小写转换为大写

>>> name = 'tom'
>>> name.upper()
'TOM'
>>> mys = 'tom123'
>>> mys.upper()
'TOM123'
>>> 
>>> name = 'tom'
>>> name.title()  # title 将单词的首字母大写
'Tom'
>>> 

9) strip 去空格

>>> a= '  abcde  '
>>> a.strip()
'abcde'
>>> 


10) isalpha 是否为26个字母


判断所有的字符串是否是26个字母,包括大小写字母

>>> name = 'jack'
>>> name.isalpha()
True
>>>
>>> name = 'jack1'
>>> name.isalpha()
False
>>> 

11) isdigit 是否为全部10个数字字符


判断是否所有的字符都是0-9的字符,如果一个不是,返回False,否则返回True

>>> num = '123'
>>> num.isdigit()
True
>>> num1 = '123a'
>>> num1.isdigit()
False
>>> 

12 ) isalnum 是否为26个字母或者10个数字字符

>>> num2 = 'abc123'
>>> num2.isalnum()
True
>>> num3  = 'abc123$'
>>> num3.isalnum()
False
>>> 

字符串格式化


字符串format()格式化方法.

前面说过%百分符格式化方法。Python官 方最近逐步在推广str.format()方 法的格式化。

tpl = “i am {}, age {}, {}”.format(“'seven”, 18, ‘alex’)

>>> mystr = 'i am %s age:%d sex:%s'%('jack',18,'男')
>>> mystr
'i am jack age:18 sex:男'
>>> 
>>> mystr = 'i am {} age:{} sex:{}'.format('jack',18,'男')
>>> mystr
'i am jack age:18 sex:男'
>>> 


相关文章
|
1天前
|
索引 Python
python字符串(str)
【5月更文挑战第8天】
9 3
|
1天前
|
Python
【Python操作基础】——字符串
【Python操作基础】——字符串
|
1天前
|
Python
【Python操作基础】——数据类型
【Python操作基础】——数据类型
|
1天前
|
Python
Python注意字符串和字节字面量
【5月更文挑战第7天】Python注意字符串和字节字面量
14 4
|
1天前
|
Python
Python字符串和字节不要混淆str.format()和bytes.format()
【5月更文挑战第6天】Python字符串和字节不要混淆str.format()和bytes.format()
8 1
|
1天前
|
Python
Python字符串和字节使用正确的编码/解码
【5月更文挑战第6天】Python字符串和字节使用正确的编码/解码
7 2
|
1天前
|
存储 Python
python字符串和字节明确数据类型
【5月更文挑战第6天】python字符串和字节明确数据类型
10 2
|
1天前
|
Python
Python避免在字符串和字节之间混淆
【5月更文挑战第5天】Python避免在字符串和字节之间混淆
16 3
|
1天前
|
数据安全/隐私保护 开发者 Python
【Python 基础】检查字符串是否只包含数字和字母?
【5月更文挑战第8天】【Python 基础】检查字符串是否只包含数字和字母?
|
1天前
|
Python
【Python 基础】如何将一个字符串转化为全大写和全小写?
【5月更文挑战第8天】【Python 基础】如何将一个字符串转化为全大写和全小写?