Python🐍

python - string(1)

2020-08-31  本文已影响0人  Pingouin

strings

# give a length of string 
len(string)

loop through strings

fruit = 'banana'
index = 0
while index < len(fruit):
  letter = fruit[index]
  print(index, letter)
  index = index + 1
fruit = 'banana'
for letter in fruit: 
  print(letter)
# for loop looks shorter

loop and counting

word = 'banana'
count = 0
for letter in word:
  if letter == 'a':
    count += 1
print(count)

- look deeper into 'in'

more string operation

1. slicing strings

s = 'Monty Python'
print(s[0:4]) # the second number, here is 4, is one beyond the end of the slice 
# "up to but not including"
print(s[6:7])
print(s[6:20])
print(s[:])

2. string concatenation

a = 'hello'
b = a + 'there'
print(b)
c = a + ' ' + 'there'
print(c)
fruit = 'banana'
'n' in fruit 
# >>> True
if 'a' in fruit:
  print('Found it')

3. string library

string.lower()
print('HI.There'.upper())
type('string1') #返回class
dir('string1') #返回所有该数据类型可用的内部的函数

4. search a string, make everything upper case

fruit = 'banana'
pos = fruit.find('ana') # 注意find函数找的是第一个
print(pos)
aa = fruit.find('z')
print(aa)

5. search and replace

greet = 'hi ke? ke!'
nstr = greet.replace('ke', 'daidai')
print(nstr)

6. stripping whitespace

greet = '   hi ke.     '
greet.lstrip()
greet.rstrip()
greet.strip() # remove both beginning and ending whitespace, not the middle!!!

can be tab/newline

7. prefixes

line = 'what is your name?'
line.startswith('what')

8.parsing and extracting

data = 'From ke.zhang@ugent.be sat Jan 5 09:00:10 2020'
atpos = data.find('@')
print(atpos)
sppos = data.find(' ',atpos) # 从atpos之后的空格
print(sppos)
host = data[atpos+1:sppos]
print(host)

练习

上一篇 下一篇

猜你喜欢

热点阅读