字符串操作

字符串的变换

1.首字母变大写:

s = "aBcDefg"
s1 = s.capitalize()
print(s1) #Abcdefg

2.全部变小写:

s1 = s.lower()
print(s1) #abcdefg

3.**全部变大写:

s1 = s.upper()
print(s1)#ABCDEFG

4.字符串中的大小写转换:

s1 = s.swapcase()
print(s1) #AbCdEFG

5.每个单词的首字母大写: 只要不是字母在字符串里就会被拆开,之后第一个字母大写

s = "aBcD ef g"
s1 = s.title()
print(s1) #Abcd Ef G

 

字符串的切来切去

1.把原字符串拉长30个单位:

s = "abcdefg"
s1 = s.center(30,"-")
print(s1)

2.**去除字符串两边的空格, 空白, \t, \n

s = "   abcdefg    "
s1 = s.strip()
print(s1) #abcdefg

3.删除字符串两边指定的内容:

s = "A   abc  defg   B"
s1 = s.strip("AB")
print(s1) #   abc  defg   
删除了两边的AB,但是之前字符串里的空格没有被删除

4.**字符串中字符的替换:

s = "abcdefg   B"
s1 = s.replace("B","xy")
print(s1) #abcdefg   xy

5.**切片, 切出来的结果是一个list

s = "abcdefg   B"
lst = s.split("d")
print(lst)   #['abc', 'efg   B']

 6.格式化输出

s = "我叫{},我今年{},我喜欢{}".format("周杰伦","40","昆凌")
print(s) #我叫周杰伦,我今年40,我喜欢昆凌

s1 = "我叫{1},我今年{0},我喜欢{2}".format("周杰伦","40","昆凌") #可以指定位置
print(s1) #我叫40,我今年周杰伦,我喜欢昆凌

s2 = "我叫{name},我今年{age},我喜欢{hobby}".format(hobby="周杰伦",age="40",name="昆凌")
print(s2) #我叫昆凌,我今年40,我喜欢周杰伦

 

1.**以...开头,以...结尾:

s = "abcdefg"
print(s.startswith("a"))#True

s = "abcdefdkjmcccefg"
print(s.endswith("g"))#True

2.查看字符串中某元素出现的次数:

s = "abcdefdkjmcccefg"

print(s.count("c"))  #4

3.找出字符串中某一个元素的位置索引值; 如果元素不在字符串中,会返回值 -1

s = "abcdefdkjmcccefg"

print(s.find("c")) #2  一般找出来的是第一次出现的位置
print(s.find("z")) #-1

4.查找字符串中某一个元素的位置,如果不在字符串中,找不到就会报错

s = "abcdefdkjmccffcefg"

print(s.index("f")) #5  一般找出来的是第一次出现的位置
print(s.index("z")) #ValueError: substring not found
找出字符串中第二个 e 的位置
name = "aleX leNb"
index = 0
for i in name:
     if i == "e":
         print(index)  # 2  6
     index = index+1  

5.字符串条件的判断 

s = "123"
print(s.isdigit()) #True  字符串是数字组成
s = "abc"
print(s.isalpha()) #True  字符串是字母组成
s = "123abc"
print(s.isalnum()) #True  字符串是数字和字母组成

6.**判断字符串的长度:

s = "abcde"
print(len(s)) #5

7.**字符串的迭代:

s = "abcde"
for i in s:
    print(i)

a
b
c
d
e
s = "刘能赵四"
print(s[0])
print(s[1])
print(s[2])
print(s[3])

刘
能
赵
四

8.**字符串的遍历:

s = "刘能赵四"
n = 0
while n < len(s):
    print(s[n])
    n = n + 1

刘
能
赵
四

 

posted on 2018-08-05 11:16  KD_131  阅读(158)  评论(0编辑  收藏  举报