1、字符串定义方式
a = 'hello'
b = "world"
c = 'what\'s up'
print(a)
print(b)
print(c)
单引号需要转义后才能输出
2、字符串特性
1、索引:下标运算符[]
str = 'python'
print(str[0])
print(str[4])
一个字符串是一个字符序列,可以使用索引来访问字符串中的一个字符,下表是基于0的,即下表范围为从0到len(s)-1
2、切片:截取运算符[start:end]
切片的规则:s[start: end:step] 从start开始到end-1结束,步长:step
s = 'hello'
print(s[0:3])
print(s[0:4:2])
#显示所有字符
print(s[:])
#显示前3个字符
print(s[:3])
#对字符串倒叙输出
print(s[::-1])
#除了第一个字符以外,其他全部显示
print(s[1:])
3、重复:*运算符
s = 'hello'
print(s * 3)
4、连接:+运算符
s = 'hello'
print(s + ' ' 'world')
5、成员操作符 :in和not in
s = 'hello'
print('o' in s) #return True
print('o' not in s) #return False
print('a' in s) #return False
print('a' not in s) #return True
6、for循环(迭代)
一个字符串是可迭代的。可以使用一个for循环来顺序遍历字符串中所有字符
s = 'hello'
for i in s:
print(i)
3、字符串处理函数
1、字符串判断大小和写数字:isdigit
判断字符串中每个元素是否为什么类型,其中只要有一个字符不满足,即返回False
s1 = '123'
s2 = '1a23'
print(s1.isdigit())
print(s2.isdigit())
2、判断某个字符串是否为标题(第一个字符大写,其余字母小写)返回值为True|False
print('Hello'.istitle())
print('hello'.istitle())
3、转换字符串:upper、lower
print('hello'.upper()) ###小写转换为大写
print('hello'.isupper()) ###判断是否为大写
print('HELLO'.lower()) ###大写转换为小写
print('HELLO'.islower()) ###判断是否为小写
4、判断是否是数字或者字母:isalnum、isalpha
print('hello123'.isalnum())
print('123'.isalpha())
print('aaa'.isalpha())
5、字符串去除两边空格
字符’’ \t \f \r
n都可认为是空白字符
###去除左边空格:lstrip
s = '\tWelcome to Python\t'
s1 = s.lstrip()
print(s)
print(s1)
###去除右边空格:rstrip
s = '\tWelcome to Python\t'
s1 = s.rstrip()
print(s)
print(s1)
###去除两边空格:strip
s = '\tWelcome to Python\t'
s1 = s.strip()
print(s)
print(s1)
6、字符串开头结尾匹配
###匹配开头:startswitch
str = 'http://172.25.254.55/index.html'
if str.startswith('http'):
print('get web')
else:
print('Not Found')
###匹配结尾:endswitch
# filename = 'hello.loggg'
#
# if filename.endswith('.log'):
# print(filename)
# else:
# print('error filename')
7、字符串的搜索与替换
###搜索:find
str = 'Welcome to Python Welcome'
print(str.find('Welcome')) ###找到子串,返回最小的索引
print(str.rfind('Welcome')) ###找到子串,返回最大的索引
###替换:replace
str = 'Welcome to Python Welcome'
print(str)
print(str.replace('Welcome', 'Hello'))
8、字符串对齐:center
print('Welcome to Python'.center(50,'*'))
print('Welcome to Python'.center(50,' '))
print('Welcome to Python'.ljust(50,'*'))
print('Welcome to Python'.rjust(50,'*'))
9、字符串的统计:count
s = 'Welcome to Python'
count = s.count('e')
print(count)
###统计字符串长度:len
s = 'Welcome to Python'
length = len(s)
print(length)
10、字符串分离和连接
###分离:split
s = 'Welcome to Python'
s1 = s.split()
print(s)
print(s1)
print(s1[::-1])
###连接:join
date = '2018-01-17'
date1 = date.split('-')
print(date1)
print(''.join(date1))
print('-'.join(date1))