一、字符串
通俗的说以单引号或者双引号引起来的任意文本都是字符串 如:'abc' "def" "123"
-
#创建字符串
-
str1 = "TA is a good man!"
-
#字符串连接
-
str2 = "TA is a "
-
str3 = "good man"
-
str4 = str2 + str3
-
print("str2 = ",str2)
-
print("str3 = ",str3)
-
print("str4 =",str4)
-
#输出重复字符串
-
str5 = "good "
-
str6 = str5*3
-
print("str6 = ",str6)
-
#访问字符串中的某一个字符
-
#通过索引下标查找字符,索引从0开始
-
#格式:字符串名[下标]
-
str7 = "sunck is a handsome man!"
-
print("str7[1] =",str7[1])
-
str6 = sunck is a
-
str7 = good man
-
str8 = sunck is a good man
-
str6 = good good good
-
str7[1] = u
-
str8 = "TA is a good man!"
-
#从给定下标出开始截取到给定下标之前
-
str9 = str8[6:15]
-
#从头截取到给定下标之前(从开始截取或者截取到最后一个下标处,开头的0和末尾的下标可不写)
-
str10 = str8[0:5]
-
#从给定下标处开始截取到结尾
-
str11 = str8[16:]
-
print("str9 = ",str9)
-
print("str10 = ",str10)
-
print("str11 = ",str11)
-
str9 = is a good
-
str10 = TA
-
str11 = man!
-
#一个单词是否在字符串中,在字符串中返回True,不在字符串中返回False
-
str12 = "TA is a good man!"
-
print("good"in str12)
-
print("good"not in str12)
-
True
-
False
-
#len(str)
-
#返回字符串的长度(字符个数)
-
print(len("TA is a good man"))
-
#lower(str)转换字符串中的大写字母为小写字母
-
str13 = "TA is a Good Man"
-
str14 = str13.lower()
-
print("str14 =",str14)
-
print("str13 =%s"%(str13))
-
#upper()转换字符串中的小写字母为大写字母
-
str15 = "TA is A Good Man"
-
print(str15.upper())
-
#swapcase()大写变小写,小写变大写
-
str16 = "TA iS A Good Man"
-
print(str16.swapcase())
-
#capitalize()首字母大写,其余小写
-
str17 = "Sunck is A Good Man"
-
print(str17.capitalize())
-
#每个单词的首字母大写
-
str18 = "Sunck is A Good Man"
-
print("str18 =",str18.title())
-
16
-
str14 = ta is a good man
-
str13 =TA is a Good Man
-
TA IS A GOOD MAN
-
ta Is a gOOD mAN
-
Ta is a good man
-
str18 = Ta Is A Good Man
-
num = 10
-
str19 = "TA is a good man!"
-
f = 1.02345
-
f = 10.1234
-
print("num =",num)
-
print("num =%d,str19 = %s,f = %f,f = %.3f"%(num,str19,f,f))
[python] view plain copy
- <code class="language-python">num = 10
- num =10,str19 = TA is a good man!,f = 10.123400,f = 10.123</code>
-
#%d占位符,小数是%f占位,默认小数点后六位,%.3f表示精确到小数点后3位且会四舍五入
-
print("num =%d\nstr19 = %s\nf = %f\nf = %.3f"%(num,str19,f,f))
-
#\n转义字符换行,且只表示一个字符
-
num =10
-
str19 = TA is a good man!
-
f = 10.123400
-
f = 10.123
-
#将一些字符转成有特殊含义的字符
-
# \n 换行 (\ 转义字符)
-
#\\n 前一个\把后面得\n转义成普通字符,所以在这里前一个\才是转义字符
-
print("TA \n is\ a \good\ man!")
-
print("TA \\n is\ a \good\ man!")
-
TA
-
is\ a \good\ man!
-
TA \n is\ a \good\ man!
-
#\'' "" 转义单引号 双引号
-
print('Tom is a \'good\'man')
-
print('Tom is a \"good\"man')
-
Tom is a 'good'man
-
Tom is a "good"man
-
#如果字符串内有很多换行,写在一行不好阅读,用\n换行或者用第二种写法
-
print("TA\nis\na\ngood\nman")
-
print('''TA is a good man!
-
TA is a nice man!
-
TA is a handsome man!
-
''')
-
TA
-
is
-
a
-
good
-
man
-
TA is a good man!
-
TA is a nice man!
-
TA is a handsome man!
-
#\t 制表符 代表四个空格
-
print("TA\tgood")
-
#如果字符中有很多字符串都需要转义,就需要加入好多\,为了简化,python允许用r表示内部的字符串默认不转义
-
print(r"\\\t\\")
-
TA good
-
\\\t\\