字符串常用操作方法总结

# -*- coding:utf-8 -*-
'''字符串常用操作方法总结,部分内容整理自网上'''
test_str='The Zen of Python, by Tim Peters'

'''一些简单实用的判断函数:
isalnum() #是否全是字母和数字,并至少有一个字符
isalpha() #是否全是字母,并至少有一个字符
isdigit() #是否全是数字,并至少有一个字符
isspace() #是否全是空白字符,并至少有一个字符
islower() #S中的字母是否全是小写
isupper() #S中的字母是否便是大写
istitle() #S是否是首字母大写的
startwith(prefix[,start[,end]]) #是否以prefix开头
endwith(suffix[,start[,end]]) #以suffix结尾
 '''
print 'so what?!'.isalnum()#False
print 'anha1230'.isalnum()#True

print('#' * 40)

'''find 在一个较为长的字符串中查找子串,并返回子串所在位置的最左端索引,若没有则返回-1'''
print test_str.find('hello')# 没有 返回-1
print test_str.find('The')#子串所在位置的最左端索引
print test_str.find('Python')#子串所在位置的最左端索引
print('#' * 40)
'''此方法还接受可选择的起始点和结束点,注意是[起始,结束)区间'''
print test_str.find('The',1)# 没有 返回-1
print  test_str.find('The',0,2)# 没有 返回-1
print  test_str.find('The',0,3)# 没有 返回-1

print('#' * 40)

'''in 若只是想知道子串是否(bool)存在于较长的字符串 ,可以用 in'''
if 'Zen' in test_str:
    print 'Zen is found in test_str!'

print('#' * 40)

'''join 连接字符串'''
sep='+'
alist=['1','2','3','4','5']#注意这里的list的元素必须是str类型的才可以使用sep来join他们,若是int型的则不行
print sep.join(alist)
print test_str.split()#默认参数是空格, ['The', 'Zen', 'of', 'Python,', 'by', 'Tim', 'Peters']

print('#' * 40)

'''split join的逆方法,拆分字符串'''
print '1+2+3+4+5'.split('+')

print('#' * 40)


'''replace 替换'''
print test_str.replace('Zen','Hen')

print('#' * 40)

'''strip 去除str两端的空格,不包括中间'''
print 'hello world!'.strip()#hello world!
print '    hello world!    '.strip()#hello world!
'''也可以指定去除两端的字符'''
print '****!!!!!hello ! world!!!!!*****'.strip('!*')#hello ! world


print('#' * 40)
'''capitalize 将字符串首字符转换为大写'''
print 'how are you!'.capitalize()#How are you!

print('#' * 40)

'''capwords 将字符串的每个字母的第一个字符转换为大写
其原理是 用split()函数分开,然后用capitalize()把首字母变成大写,最后用join()合并到一起 '''
from string import capwords
print capwords('how are you!')#How Are You!

print('#' * 40)

'''upper/lower 分别将字符串的所有字母转换为大写/小写'''
print 'how are you!'.upper()#HOW ARE YOU!
print 'HOW ARE YOU!'.lower()#how are you!

print('#' * 40)

'''swapcase 转换大小写'''
print test_str.swapcase()#tHE zEN OF pYTHON, BY tIM pETERS
print test_str.swapcase()#The Zen of Python, by Tim Peters

print('#' * 40)

'''translate 与replace一样 但优点是可以同时进行多个替换(结合maketrans函数返回的转换表),replace则只能处理单个字符串'''
from string import  maketrans
table = maketrans('Hen','Zen')#定义转换表,指定用第二个参数代替第二个参数的对应关系,maketrans接受两个等长的字符串,
print test_str.translate(table)#The Zen of Python, by Tim Peters
print test_str.translate(table,' ')#还可以在第二个参数 指定要删除的字符(s)  #TheZenofPython,byTimPeters

print('#' * 40)

'''format 如下,本段部分内容转载自http://www.cnblogs.com/hongten/archive/2013/07/27/hongten_python_format.html'''

#使用'{}'占位符
print('I\'m {},{}'.format('Hongten','Welcome to my space!'))

print('#' * 40)

#也可以使用'{0}','{1}'形式的占位符
print('{0},I\'m {1},my E-mail is {2}'.format('Hello','Hongten','hongtenzone@foxmail.com'))
#可以改变占位符的位置
print('{1},I\'m {0},my E-mail is {2}'.format('Hongten','Hello','hongtenzone@foxmail.com'))
#从这里也可以知道使用%格式字符串,要求变量有严格的次序,而.format()方法允许任意排列和重复使用
print('#' * 40)

#使用'{name}'形式的占位符
print('Hi,{name},{message}'.format(name = 'Tom',message = 'How old are you?'))

print('#' * 40)

#混合使用'{0}','{name}'形式
print('{0},I\'m {1},{message}'.format('Hello','Hongten',message = 'This is a test message!'))

print('#' * 40)

#进制与精度转换,b、d、o、x分别是二进制、十进制、八进制、十六进制
print("{0:d} - {0:x} - {0:o} - {0:b} ".format(21))#21 - 15 - 25 - 10101
#{0:d}中 0代表的是第0个变量,冒号后面就是要格式化的格式
print '{0:.2f}'.format(321.33345)#321.33
#也可写成  print '{:.2f}'.format(321.33345)  #只有一个参数时可以不用标记是第几个变量
print('#' * 40)

#对齐与填充,^、<、>分别是居中、左对齐、右对齐,后面带宽度
#:号后面带填充的字符,只能是一个字符,不指定的话默认是用空格填充
print '{:^5}'.format('123')#' 123 '
print '{:>5}'.format('123')#'  123'
print '{:$>5}'.format('123')#'$$123'


'''小技巧: 翻转字符串'''
print test_str[::-1]#sreteP miT yb ,nohtyP fo neZ ehT

print('#' * 40)

'''小技巧: 千位分隔符'''
print '{:,}'.format(1234567890)#1,234,567,890

''' 更加详细的请看这里: python字符串操作和string模块代码分析 http://blog.chinaunix.net/uid-25992400-id-3283846.html'''

<think>嗯,用户需要JavaScript中操作字符串的方法总结。首先,我得回忆一下JavaScript中有哪些常用字符串操作方法。可能包括基本操作如拼接、截取,还有ES6新增的方法。 记得最基础的是length属性,获取字符串长度。然后charAt()和charCodeAt()用来获取特定位置的字符或其编码。slice()、substring()、substr()这些用于截取子串,不过要注意它们的参数区别。 concat()方法可以拼接字符串,不过通常用加号更方便。indexOf()和lastIndexOf()查找子串位置,includes()、startsWith()、endsWith()是ES6新增的,返回布尔值。 大小写转换有toLowerCase()和toUpperCase()。trim()去除空白,ES6还加了trimStart()和trimEnd()。split()分割成数组,replace()替换内容,match()正则匹配。 padStart()和padEnd()是ES6的填充方法。repeat()重复字符串字符串模板用反引号,可以嵌入变量和表达式。 可能需要区分不同方法的兼容性,比如ES6的方法在旧浏览器中的支持情况。还要注意参数是否包含起始结束位置,比如substring和slice的区别,substr的第二个参数是长度。 用户可能需要实际例子,所以每个方法最好附上代码示例。还要提醒常见的陷阱,比如字符串不可变性,这些方法返回新字符串而非修改原字符串。 最后,考虑用户可能的应用场景,比如表单验证、数据处理等,可以给出相关方法的使用建议。是否要比较不同方法的性能?不过可能对初学者来说,易用性更重要。 检查是否有遗漏的重要方法,比如search()、localeCompare(),或者字符串迭代器方法。不过可能基础总结不需要太深入,保持简洁明了。 确保分类清晰,比如基本操作、查找、修改、转换、ES6特性等。这样用户查阅起来更方便。可能需要用列表或代码块展示,但根据用户要求,这里用Markdown格式。 还需要注意中英文术语的一致性,比如“方法”对应“method”,避免混淆。最后,生成相关问题,帮助用户深入理解,比如问不同截取方法的区别,或如何高效拼接字符串等。</think># JavaScript字符串操作方法汇总 ## 一、基础操作方法 1. **获取长度** `length` 属性获取字符串长度 ```javascript let str = "hello"; console.log(str.length); // 5 ``` 2. **访问字符** - `charAt(index)` 获取指定位置字符 - `charCodeAt(index)` 获取字符的Unicode编码 ```javascript "abc".charAt(1); // "b" "abc".charCodeAt(0); // 97 ``` 3. **截取字符串** - `slice(start, end)` 支持负数索引 - `substring(start, end)` 自动调整参数顺序 - `substr(start, length)` 第二个参数为长度 ```javascript "javascript".slice(0,4); // "java" ``` ## 二、字符串操作 4. **拼接字符串** `concat()` 方法或 `+` 运算符 ```javascript "Hello".concat(" World"); // "Hello World" ``` 5. **查找子串** | 方法 | 功能 | ES6 | |---|---|---| | `indexOf()` | 首次出现位置 | × | | `lastIndexOf()` | 最后出现位置 | × | | `includes()` | 是否包含子串 | √ | | `startsWith()` | 是否以子串开头 | √ | | `endsWith()` | 是否以子串结尾 | √ | ```javascript "vue".includes("ue"); // true ``` ## 三、字符串修改 6. **大小写转换** `toLowerCase()` 和 `toUpperCase()` ```javascript "React".toLowerCase(); // "react" ``` 7. **去除空白** `trim()` 及其变体方法 ```javascript " text ".trimStart(); // "text " ``` 8. **替换内容** `replace(searchValue, newValue)` ```javascript "2023-08".replace(/-/g, "/"); // "2023/08" ``` ## 四、类型转换 9. **分割字符串** `split(separator)` 转换为数组 ```javascript "a,b,c".split(","); // ["a","b","c"] ``` 10. **重复生成** ES6 `repeat(count)` ```javascript "na".repeat(2); // "nana" ``` ## 五、ES6+特性 11. **模板字符串** 使用反引号 `` ` `` 支持多行字符串和插值 ```javascript let name = "Alice"; `Hello ${name}`; // "Hello Alice" ``` 12. **填充方法** `padStart(targetLength, padString)` 和 `padEnd()` ```javascript "5".padStart(3, "0"); // "005" ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值