Python字符串(String)类型:
字符串或串(String)是由数字、字母、下划线组成的一串字符。
一般记为 :
s="a1a2···an"(n>=0)
它是编程语言中表示文本的数据类型。
python的取值顺序:
1)从左到右索引默认0开始的,最大范围是字符串长度少1
2)从右到左索引默认-1开始的,最大范围是字符串开头
取值遵循包前不包后原则。
举例说明:
a='abcdefghijk'
![]()
加号(+)是字符串连接运算符,星号(*)是重复操作。
Python支持格式化字符串的输出
最基本的用法是讲一个值插入到一个有字符串格式化%s的字符串中。
举例说明:
name='Bob'
age=16
print ("%s is %d-year-old" %(name,age))
输出结果:Bob is 16-year-old
Python字符串查找与替换
举例说明:
s = 'HelloabcdWord'
代码 |
含义 |
输出 |
print s.isalpha() |
查看字符串是否全由字母组成 |
True |
print s.isdigit() |
查看字符串是否全由数字组成 |
False |
print s.isspace() |
查看字符串是否全由空格组成 |
False |
print s.startswith('Hello') |
查看字符串是否以‘Hello’开头 |
True |
print s.endswith('World') |
查看字符串是否以‘Word’结尾 |
False |
Python字符串中的字母大小写转换
举例说明:
代码: 解释
a = 'In\na line' 不加r的字符串中\n会使字符串换行
b = r'In\na line' 加r的字符串中转义字符不会被转义
print a
print b
print a.lower() 转小写
print b.upper() 转大写
输出结果:
In
a line
In\na line
in
a line
IN\NA LINE
Python字符串批量替换
举例说明:
代码1:
weather = 'rainy day'
bag = 'nothing in the bag'
if weather.find('rain')!=-1:
bag=bag.replace('nothing','umbrella')
print bag
解释:
如果匹配到 'rain’'则将'noting’只会为'umbrella'
find函数匹配不到所找的字符返回值为‘-1’。
输出结果:
umbrella in the bag
代码2:
a=raw_input()
if a.find(' ')!=-1:
a=a.replace(' ','%20')
print a
解释:
判断输入的字符串是否含有空格,用%20替换空格后输出
Python字符串总结就到这里啦~谢谢朋友cy_ll的指点~也希望大家多多指教~