7天玩转Python(四)Python字符串

字符串的格式化

字符串格式化的语法:“s%”%str1

                                         "s%s%"%(str1,str2)

str1 = "version"
num = 1
print("str:%s" % str1)
print("num:%d str1:%s" % (num, str1))

字符串对其操作

word = "version3.0"
print(word.center(20))               #变量两侧输出5个空格
print(word.center(20, "*"))          #变量两侧各输出5个*
print(word.ljust(0))                 #输出结果左对齐
print(word.rjust(20))                #输出20个字符,左边占10个空格

去字符串的转义符

word = "\thello world\n"
print("直接输出:", word)
print("strip()", word.strip())     #去除转义字符
print("lstrip()", word.lstrip())   #去除左转义字符
print("rstrip()", word.rstrip())   #去除右转义字符

字符串的合并

python使用“+”连接字符串,python会根据“+”两侧的类型,决定执行连接操作或加法运算。如果两侧都是字符串执行连接操作;如果两侧都是数字类型则执行加法运算,两侧不同的类型,将抛出异常。

str1 = "hello"
str2 = "python"
result = str1+str2
print(result)

python还提供了join()函数进行字符串的合并

strs = ['hello',"python"]
print(" ".join(strs))

字符串的截取

使用索引截取子串

word = "python"
print(word[4])

特殊切片截取子串

s1 = 'hello python'
print(s1[0:3])
print(s1[::2])
print(s1[1::2])

split()获取子串

sentence = "Bob said:1,2,3,4"
print(sentence.split())         #空格截取子串
print(sentence.split(","))      #逗号截取子串
print(sentence.split(",", 2))    #两个都好截取子串

字符串的比较

python中用“==”和“!=”比较两个字符串的内容

str1 = 1
str2 = '1'
if str1 == str2:
    print("相等")
else:
    print("不相等")

if str(str1) == str2:
    print("相等")
else:
    print("不相等")

startwith()和endwith()

word = "hello world"
print("hello" == word[0:5])
print(word.startswith("hello"))
print(word.endswith("ld",  6))
print(word.endswith("ld",  6,  10))
print(word.endswith("ld",  6,  len(word)))

字符串的反转

通过切片将字符串反序输出

print(word[::-1])
for i in range((len(word)), 0, -1):
   print(word[i-1])

字符串的查找和替换

字符串的查找用find()方法,返回字符第一次出现时候的索引

word1 = "this is a apple"
print(word1.find("a"))
print(word1.rfind("a"))

python使用replace()实现字符串的替换

sentence = "hello world,hello china"
print(sentence.replace("hello", "hi"))
print(sentence.replace("hello", "hi", 1))

 

 

 

 

你可能感兴趣的:(Python)