字符串

1 字符串中*的使用

  *可使字符串重複n次spa

1 print('hello world ' * 2)  # hello world hello world 

2 索引獲取字符串的字符元素

1 print('hello world'[2:])  # llo world

3 in成員符

1 print('el' in 'hello')  # True

4 字符串格式化

1 name = 'Bob'
2 msg = 'my name is %s' % name
3 print(msg)  # my name is Bob

5 字符串拼接

  採用+(建議儘可能不要採用此方法,效率低,時間複雜度爲平方級)code

1 name = 'Bob'
2 age = '20'
3 msg = name + ' is ' + age + ' years old!'
4 print(msg)  # Bob is 20 years old!

  採用join方法blog

    字符串是join前面的那一字符串爲拼接間隔索引

1 name = 'Bob'
2 age = '20'
3 msg = name + ' is ' + age + ' years old!'
4 print(msg)  # Bob is 20 years old!
5 msg_join = ' '.join([name, 'is', age, 'years old!'])
6 print(msg_join)  # Bob is 20 years old!

6 字符串經常使用的內置方法

  6.1 count() 能夠計算參數中的字符串在原字符串中出現的數量ip

1 string = 'hello kitty'
2 count = string.count('l')
3 print(count)  # 2

  6.2 center() 字符串

1 string = 'title'
2 msg = string.center(50, '-')
3 print(msg)  # ----------------------title-----------------------

  6.3 startswith()string

    能夠判斷待處理的字符串是否是本身想要的字符串it

1 string = 'title'
2 print(string.startswith('t'))  # True

  6.4 find()class

    查找參數中的字符串並返回索引,若找不到就返回-1效率

1 st = 'hello world'
2 index = st.find('w')
3 print(index)  # 6
4 print(st.find('a'))  # -1

  6.5 index()

    和find()差很少,只是在找不到的時候報錯

1 st = 'hello world'
2 index = st.index('w')
3 print(index)  # 6
4 print(st.index('a'))  # ValueError: substring not found

  6.6 lower()

    將字符串中的大寫字母變成小寫字母

1 st = 'Hello World'
2 st_lower = st.lower()
3 print(st_lower)  # hello world

  6.7 upper()

    將字符串中的小寫字母變成大寫字母

1 st = 'Hello World'
2 st_upper = st.upper()
3 print(st_upper)  # HELLO WORLD

  6.8 strip()

    將待處理的字符串的空格,換行,製表符去掉

1 st = '      hello world\n'
2 st_strip = st.strip()
3 print(st_strip)  # helloworld
4 print(len(st_strip))  # 11

  6.9 replace()

1 st = 'hello world'
2 st_replace = st.replace('world', 'Bob')
3 print(st_replace)  # hello Bob

  6.10 split()

    將字符串按照某字符進行分割,返回一個字符串元組

1 st = 'my old boy'
2 st_split = st.split(' ')
3 print(st_split)  # ['my', 'old', 'boy']
相關文章
相關標籤/搜索