1. 字符串变量
# 注意引号的配对
a = "Hello, welcome to Python"
print("The string a is:", a)
print()
# 占位符
print("The length of this string <%s> is %d" % (a, len(a)))
print()
print("The type of a is", type(a))
The string a is: Hello, welcome to Python
The length of this string <Hello, welcome to Python> is 24
The type of a is <class 'str'>
a = "Hello, welcome to Python"
print("The first character of a is %s" % a[0])
print("The first five characters of a are %s" % a[0:5])
print("The last character of a is %s" %a[-1])
print("The last two characters of a is %s"%a[-2:])
print("The last character of a is %s"%a[len(a)-1])
The first character of a is H
The first five characters of a are Hello
The last character of a is n
The last two characters of a is on
The last character of a is n
1.1内置函数find()
a="erkgjier"
for i in a:
print(i)
a.find('e') #find()函数找索引位置
a.find('g')
print("The index of fist <e> is:",a.find('e'))
pos=0
for i in a:
pos+=1
if i=='e':
print(pos)
e
r
k
g
j
i
e
r
The index of fist <e> is: 0
1
7
1.2find()找所有位置索引
a='oaoaoaoa'
pos=a.find('o') #内置函数find()只能确定最先出现的o的位置
print(pos)
#如何找到所有o的位置,要在发现o之后,截取其后的字符串,再执行find操作
while True:
print(pos)
new=a[pos+1:].find('o')
if new==-1:
break
pos=new+pos+1
0
0
2
4
6
1.3利用split()分割字符串
#利用split()分割字符串
str1="a b c d e f g"
str2=str1.split(' ')#按空格分隔
print(str2)
['a', 'b', 'c', 'd', 'e', 'f', 'g']
1.4去除字符串中的特定字符
#去除字符串种特定的字符,通常我们在文件中读取的一行都包含换行符
a="oneline\n"
print("Currently, the string <a> is",a,"The length of string <a> is",len(a))
#换行符占一个字符,strip()去掉
a=a.strip()
print("Currently, the string <a> is",a,"\nThe length of string <a> is",len(a))
a=a.strip('o')
print("Currently, the string <a> is",a, "\nThe length of string <a> is",len(a))
a=a.strip('one')
print("Currently, the string <a> is",a,"\nThe length of string <a> is",len(a))
Currently, the string <a> is oneline
The length of string <a> is 8
Currently, the string <a> is oneline
The length of string <a> is 7
Currently, the string <a> is neline
The length of string <a> is 6
Currently, the string <a> is li
The length of string <a> is 2
1.5替换字符串
#字符串的替换
a="Hello,python"
print(a)
b=a.replace("Hello","Welcome")
print(b)
c=a.replace("o","O")
print(c)
d=a.replace("o","0",1)
print(d)
Hello,python
Welcome,python
HellO,pythOn
Hell0,python
#大小写判断和转换
a="Ddsdsd"
print("All elements in %s is lowercase:%s" %(a,a.islower()))
print("Transfer all elements in %s to lowercases: %s"%(a,a.lower()))
print("Transfer all elements in %s to uppercases: %s"%(a,a.upper()))
All elements in Ddsdsd is lowercase:False
Transfer all elements in Ddsdsd to lowercases: ddsdsd
Transfer all elements in Ddsdsd to uppercases: DDSDSD
1.6字符串转数组
#字符串转数组
str1="ACTG"
a=list(str1)
print(a)
a.reverse()
print(a)
print(''.join(a))
['A', 'C', 'T', 'G']
['G', 'T', 'C', 'A']
GTCA
a="123"
print(a+'1')
print(int(a)+1)
print(float(a)+1)
#从文件或命令行参数中去除的数字都是字符串形式出现,做四则运算时要
#先用int或float转换
1231
124
124.0