python字符串处理

字符串处理

1. split拆分字符串
words="To be or not to be that is the question"
words1="hey#please#be#kind"
new_words=words.split()
newwords1=words1.split("#")
print("默认空格拆分结果:"+str(new_words))
print("使用指定符号得到拆分结果:"+str(newwords1))
默认空格拆分结果:['To', 'be', 'or', 'not', 'to', 'be', 'that', 'is', 'the', 'question']
使用指定符号得到拆分结果:['hey', 'please', 'be', 'kind']
2. strip删除字符串前后的空格
words="    To be or not to be that is the question!  "
new_words=words.strip()
print("删除字符串前后空格后:"+str(new_words))
new_words=words.strip(" To")
new_words=words.replace(" be","")
print("删除字符串前后空格后:"+str(new_words))
删除字符串前后空格后:To be or not to be that is the question!
删除字符串前后空格后:    To or not to that is the question!  
3. join连接列表的字符串
list=['2018','5','14']
list_join = "-".join(list)
print(list_join)
2018-5-14
4. 大小写转换
words="ME before YOU"
words_1=words.upper()
print("小写转化为大写得到:"+words_1)
words_2=words.lower()
print("大写转化为小写得到:"+words_2)
小写转化为大写得到:ME BEFORE YOU
大写转化为小写得到:me before you
5. 字符与ASCII码的转换
print("ASCII码65表示:"+chr(65))
print("C的ASCII码为:"+str(ord("C")))
ASCII码65表示:A
C的ASCII码为:67
6. 英文字母判断
words="my name is"
print(words.islower())   #islower检测字符串是否全部为小写,可以有其他类型字符
print(words.isupper())   #isupper检测字符串是否全部为大写,可以有其他类型字符
print(words.istitle())   #istitle()检测首字母是否为大写,且其他的为小写,而且字符串不能有空格
True
False
False
7. 组合字符判断
words="my name is"
print(words.isalnum())      #判断字符串的字符是否包含字母和数字(没有空格)
print(words.isalpha())      #判断字符串的所有字符是否都是字母(没有空格)
False
False
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Python字符串处理是指对字符串进行各种操作和处理的技术。Python提供了丰富的字符串处理方法和函数,可以方便地进行字符串的拼接、切片、查找、替换等操作。 以下是一些常用的Python字符串处理方法和函数: 1. 字符串拼接:使用"+"运算符可以将两个字符串拼接在一起,例如:`str1 + str2`。 2. 字符串切片:可以通过索引来获取字符串中的部分内容。例如,`str[1:5]`表示获取从索引1到索引4的子字符串。 3. 字符串长度:使用`len()`函数可以获取字符串的长度,例如:`len(str)`。 4. 字符串查找:可以使用`find()`、`index()`等方法来查找字符串中某个子串的位置。例如,`str.find(sub_str)`返回子串在字符串中第一次出现的位置。 5. 字符串替换:使用`replace()`方法可以将字符串中的某个子串替换为另一个子串。例如,`str.replace(old_str, new_str)`将字符串中的old_str替换为new_str。 6. 字符串分割:使用`split()`方法可以将字符串按照指定的分隔符进行分割,返回一个列表。例如,`str.split(separator)`将字符串按照separator进行分割。 7. 字符串大小写转换:使用`lower()`、`upper()`等方法可以将字符串转换为小写或大写形式。例如,`str.lower()`将字符串转换为小写形。 8. 字符串格式化:使用`format()`方法可以将变量的值插入到字符串中的占位符位置。例如,`"Hello, {}!".format(name)`将name的值插入到字符串中的占位符位置。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值