赞
踩
目录
①、在文本文件中存储数据时,常见的方法就是将各个项用逗号分隔,将出现逗号的地方分解字符串。
③、没有指定任何分解标记,它会按空白符(whit- espace)分解字符串
①、startswith() 函数:指出一个字符串是否以某个字符或某几个字符开头
②、 endswith()函数:指出一个字符串是否以某个字符或某几个字符结尾
把一个长字符串分解成多个小字符串。
string.split()
- name_string = 'xiaoming, hong, xiaohua, meihua, cherry'
- names = name_string.split(',')
- print(names)
-
- for name in names:
- print(name)
-
- 输出:
- ['xiaoming', ' hong', ' xiaohua', ' meihua', ' cherry']
- xiaoming
- hong
- xiaohua
- meihua
- cherry
- names = name_string.split(', meihua')
- print(names)
-
- for name in names:
- print(name)
-
- 输出:
- ['xiaoming, hong, xiaohua', ', cherry']
- xiaoming, hong, xiaohua
- , cherry
- names = name_string.split()
- print(names)
- for name in names:
- print(name)
-
- 输出:
- ['xiaoming,', 'hong,', 'xiaohua,', 'meihua,', 'cherry']
- xiaoming,
- hong,
- xiaohua,
- meihua,
- cherry
- print('dog' + 'sun')
-
- 输出:
- dogsun
- word =['my', 'name', 'is', 'chreey']
- print(word)
- long_string = ' '.join(word)
- print(long_string)
-
- long = 'hello '.join(word)
- print(long)
-
-
- 输出:
- ['my', 'name', 'is', 'chreey']
- my name is chreey
- myhello namehello ishello chreey
- name = 'frankenstein'
- name.startswith('F')
- name.startswith('f')
- name.startswith('frank')
- name.startswith('flop')
-
- 输出:
- >>> name.startswith('F')
- False
- >>> name.startswith('f')
- True
- >>> name.startswith('frank')
- True
- >>> name.startswith('flop')
- False
若想知道查找的字符串,是在哪个位置:
- lines = ['cake', '2 eggs', 'sode', 'instructions','mix']
- i = 0
- while not lines[i].startswith('instructions'):
- i = i + 1
-
- print(i)
-
- 输出:
- 3
- name = 'frankenstein'
-
- name.endswith('n')
- name.endswith('stein')
-
- 输出:
- >>> name.endswith('n')
-
- True
- >>> name.endswith('stein')
- True
- >>> name.endswith('soop')
- False
in: 检查某个元素是否在列表中。
- city = ['657 Maple Lane', '47 B Syreet', '95 Drive']
-
- if '657 Maple Lane' in city:
- print('include in')
-
- 输出:
- include in
in 关键字只能指出子串是不是位于检查的字符串中的某个位置,但没有告诉到底在什么位置。要得到这个位置,需要使用 index() 方法。
- city = ['657 Maple Lane', '47 B Syreet', '95 Drive']
-
- if ' Maple' in city[0]:
- print('include in')
- pos = city[0].index('Maple')
- print('found at', pos)
-
- 输出:
- include in
- found at 4
strip():剔除末尾部分,如换行符或一些多余空格
- name = 'afternoon ok?'
- short_name = name.strip('ok?')
- print(short_name)
-
- name = 'afternoon ok? '
- short_name = name.strip()
- print(short_name)
-
- 输出:
- afternoon
- afternoon ok?
把字符串从大写转换为小写或从小写转换为大写。
- str1 ='ABCDEFG'
- str2 ='hijklmn'
-
- strl1 = str1.lower()
- print(strl1)
- stru1 = str2.upper()
- print(stru1)
-
- 输出:
- abcdefg
- HIJKLMN
赞
踩
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。