字符串操作
1. 获取字符串长度
test = 'hello world'
1) python
res = len(test)
2) js
res = test.length
2. 字符串反转
test = 'hello world'
1) python
res = test[::-1]
2) js
res = test.split('').reverse().join('')
3. 去除前后空格
test = ' hello world '
1) python
res = test.strip()
2) js
res = test.trim()
4. 去除所有空格
test = ' hello world '
1) python
方法1:使用replace
res = test.replace(' ', '')
方法2:使用正则表达式
import re
pattern = re.compile(' ')
res = re.sub(pattern, '', test)
2) js
res= test.replace(/\s+/g, '')
5. 去除左边的空格
test = ' hello world '
1) python
res = test.lstrip()
2) js
res = test.replace( /^\s+/, '')
6. 去除右边的空格
test = ' hello world '
1) python
res = test.rstrip()
2) js
res = test.replace( /\s+$/g, '')
7. 查找子串
test = 'hello world'
sub = 'llo'
1) python
index = test.find(sub) # 存在返回首次出现的索引,不存在返回-1
2) js
index = test.indexOf(sub) # 存在返回首次出现的索引,不存在返回-1
8. 字符串截取
test = 'hello world'
1) python
res = test[1: 5] # ello test[start_pos: end_pos + 1]
res = test[1: ] # ello world
res = test[: -2] # hello wor
2) js
res = test.substr(2, 2) # ll 第二个参数是长度
res = test.substring(2, 2) # 第二个参数是结束位置 + 1
res = test.substring(2, 4) # ll
9. 字符串分割成数组
test = 'hello world'
1) python
res = test.split(' ')
2) js
res = test.split(' ')
10. 字符串拼接
test1 = 'hello'
test2 = 'world'
1) python
res = test1 + ' ' + test2
res = '{} {}'.format(test1, test2)
res = '%s %s' % (test1, test2)
2) js
res = test1 + ' ' + test2
res = `${test1} ${test2}`
res = test1.concat(' ', test2)
11. 判断字符串是否以某个字符串开头
test = '~hello world'
1) python
test.startswith('~') # True
2) js

浙公网安备 33010602011771号