python基础入门之三 —— 字符串

1、格式

一对引号和三对引号可以表示字符串

(三引号保留换行)

2、下标

从0开始循序向下分配

str1='abcdefg'
print(str1)
print(str1[0])
print(str1[2])

3、切片

截取字符串、列表、元组的一部分

序列 [ 开始位置下标: 结束位置下标: 步长 ]   (P.S:不包含结束位置下标的内容)

str1='0123456789'
print(str1[0:5:1]) #01234
print(str1[2:5:2]) #24
print(str1[2:5])   #234
print(str1[:5])    #01234,开始下标不写即从头开始
print(str1[2:])    #23456789,结束下标不写即直到末尾
print(str1[:])     #0123456789 啥都不写即所有

#负数测试
print(str1[::-1])  #9876543210,步长为负数倒叙
print(str1[-4:-1])  #678,下标-1表示最后一个数据
#终极测试
print(str1[-4:-1:1]) #678
print(str1[-4:-1:-1])  #下标开始到结束的方向和步长的方向冲突,没有输出

4、常用函数

4.1查找

find()

 检测某个子串是否包含这个字符串中;

如果在,返回这个子串开始的位值下标,否则返回-1.

 

index()  同find(),不同的是找不到会返回异常,报错.
count() 返回某个字串在字符串中出现的次数
rfind()、rindex() r即从右侧开始查找,其他同原函数

 exp:

#字符串序列.find ( 子串, 开始位置下标,结束位置下标 )
str1='hello world and itcast and itheima and python'
print(str1.find('and')) # 12
print(str1.find('and',15,30)) # 23
print(str1.find('ands')) #-1

#字符串序列.index ( 子串, 开始位置下标,结束位置下标 )
print(str1.index('and',15,30)) #23
#print(str1.index('ands'))  #报错

#字符串序列.count ( 子串, 开始位置下标,结束位置下标 )
print(str1.count('and',15,30))  #1
print(str1.count('and')) #3
print(str1.count('ands'))  #0

4.2 修改

replace()

 替换

split() 按照指定字符分割字符串
join() 用一个字符或字串合并成字符串,即是将多个字符串合并成一个新的字符串
大小写转换
  • capitalize():将字符串的第一个字符转换成大写
  • title():将字符串每个单词首字母转换成大写
  • lower():将字符串中大写转小写
  • upper():将字符串中小写转大写

删除空白字符

strip()

  • lstrip():删除字符串左侧空白字符
  • rsplit():删除字符串右侧空白字符
  • strip():删除字符串两侧空白字符

字符串对齐

just()

  • ljust():左对齐,并使用指定字符(默认空格)填充
  • rjust():左对齐
  • center():居中对齐
my_str="hello"
str1=my_str.rjust(10)
str2=my_str.rjust(10,"*")
print(str1)  #     hello
print(str2)  #*****hello

判断

  • startswith():检查字符串是否是以指定字串开头,是则返回True,否则返回False.

            如果设置开始和结束位置下标。则在指定范围检查

            字符串序列.startwith(字串,开始位置下标,结束位置下表)

  • endswith():同startwith(),不过指定字符串结尾
  • isalpha():判断是否都是字母
  • isdigit() 判断是否都是数字
  • isalnum();如果字符串至少又一个字符并且所有字符都是字母或者数字则返回true,否则返回false
  • isspace()判断是不是空白
old_str = 'hello world and itcast and itheima and python'

# 1、字符串序列.replace(旧子串,新子串,替换次数)
new_str = old_str.replace("and", "or")   # 没有次数,全部替换
print(old_str)   # 原有的字符串无修改,修改后的数据作为replace函数的返回值
print(new_str)
new_str1 = old_str.replace("and", "or", 10)  # 10超出子串出现次数,全部替换
print(new_str1)
new_str2 = old_str.replace("and", "or", 1)   # 1小于子串出现次数,替换1次
print(new_str2)

# 2、字符串序列.split( 分割字符,num )
list1 = old_str.split('and')
print(list1)  # ['hello world ', ' itcast ', ' itheima ', ' python']
list2 = old_str.split('and', 2)
print(list2)  # ['hello world ', ' itcast ', ' itheima and python']

# 3、字符或字串.join( 多字符串组成的序列 )
old_list = ['aa', 'bb', 'cc']
new_list = '....'.join(old_list)
print(new_list)  # aa....bb....cc
原文地址:https://www.cnblogs.com/LynHome/p/12374504.html