bloggerads

2017年8月9日 星期三

Python : string related

### Demonstrate join

>>> list = ['Nice', 'to', 'meet', 'you']
>>> ''.join(list)
Nicetomeetyou

>>> ' '.join(list)
Nice to meet you

>>>'_'.join(list)
Nice_to_meet_you


### Demonstrate split

>>> string = 'Nice to meet you'
>>> string.split()
['Nice', 'to', 'meet', 'you']

>>> string.split(' ')
['Nice', 'to', 'meet', 'you']

>>> string.split(' ', 1)
['Nice', 'to meet you']

>>> string.split(' ', 2)
['Nice', 'to', 'meet you']


### Remove all space in a string by replace
>>> string = '111 222  333      44'
>>> string.replace(' ','')
11122233344

### Remove leading and ending spaces by strip
>>> string = '    Hi, Martin       '
>>> string.strip()
Hi, Martin

### Remove duplicated spaces by split and join
>>> string = '   Hi,     Martin   '
>>> ' '.join(split())
Hi, Martin

沒有留言:

張貼留言