[Python study notes] Coursera's PY4E study notes - String

 

1. String merging

Use "+" to combine strings, pay attention to adding spaces by yourself.

example:

>>> a='Hello'
>>> b= a+ 'There'
>>> print(b)
HelloThere
>>> c=a+' '+'There'
>>> print(c)
Hello There

 

2. Use in to make logical judgments

example:

>>> fruit='banana'
>>> 'n' in fruit
True
>>> 'm' in fruit
False
>>> 'nan' in fruit
True
>>> if 'a' in fruit:
            print('Found it')

Found it

 

3. Upper and lower case

Use lower() to lowercase the subtitles of the string, and upper() to uppercase.

example:

>>> greet='Hello Bob'
>>> zap=greet.lower()
>>> print(zap)
hello bob
>>> print(greet)
Hello Bob
>>> print('Hi There'.lower())
hi there

 

4. Search string

The position of the string starts from 0. Use find() to retrieve the position of the corresponding element, and if it is two adjacent elements, return the position of the starting element.

example:

>>> fruit='banana'
>>> pos = fruit.find('na')
>>> print(pos)
2
>>> aa = fruit.find('z’)
>>> print(aa)
-1

 

5. Retrieve and replace

Use replace() to replace the corresponding element in the string with a specific character.

example:

>>> greet='Hello Bob'
>>> nstr=greet.replace('Bob','Jane')
>>> print(nstr)
Hello Jane
>>> nstr=greet.replace('o','X')
>>> print(nstr)
HellX BXb

 

6. Remove spaces

Use lstrip() to remove spaces at the beginning of a string, rstrip() to remove spaces at the end of a string, and strip() to remove spaces at the beginning and end.

example:

>>> greet ='    Hello Bob    '
>>> greet.lstrip()
'Hello Bob    '
>>> greet.rstrip()
'    Hello Bob'
>>> greet.strip()
'Hello Bob'

 

7. Prefix

Use startswith() to make logical judgments on string prefixes.

example:

>>> line='Please have a nice day'
>>> line.startswith('Please')
True
>>> line.startswith('p')
False

 

8. Decomposition and extraction

Use string slicing and find() to extract the content of the middle part of the string.

example:

>>> data='From [email protected] Sat Jan 5 09:14:16 2008'
>>> atpos=data.find('@')
>>> print(atpos)
21
>>> sppos=data.find(' ',atpos)
>>> print(sppos)
31
>>> host=data[atpos+1:sppos]
>>> print(host)
uct.ac.za

 

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325384731&siteId=291194637