Python 字符串处理常用函数

本文介绍了Python中处理字符串的多种方法,包括如何判断子串是否存在、如何进行字符串分隔、如何判断字符串是否全为数字以及如何将字符串转换为数字等实用技巧。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

Python处理字符串有很多常用函数

判断某子串是否在字符串里:

1. 使用成员操作符in

Str = 'Hello, world!\n'
sStr = '\n'
result = sStr in Str
print(result)  # True

2. 使用字符串的find()、index()火count()方法

Str = 'Hello, world!\n'
sStr = '\n'
result = Str.find(sStr) >= 0
print(result)  # True

result = Str.count(sStr) > 0
print(result)  # True

result = Str.index(sStr) >= 0
print(result)  # True

字符串分隔

使用split()

Str = 'Hello, world!\n'
Str1, Str2 = Str.split(',')
print(Str1)  # Hello
print(Str2)  #  world!

sStr = Str.split(',')
print(sStr)  # ['Hello', ' world!\n']

如果用一个对象来作为splt()的返回值,则是一个包含这两个子字符串的list。

判断字符串中是否只是数字

1. 可以使用isdigit()函数,但有的时候数字是用逗号','隔开的,我希望判断隔开后的是不是只有数字

Str = '3,5'
result = Str.isdigit()
print(result)  # False
sStr1,sStr2 = Str.split(',')
result = sStr1.isdigit()
print(result)  # True

2. 然而有时候字符串里有负数,这样可以先用strip()函数把'-'去掉,再做判断

Str = '-3,5'
result = Str.isdigit()
print(result)  # False
sStr1,sStr2 = Str.split(',')
result = sStr1.isdigit()
print(result)  # False
result = sStr1.strip('-').isdigit()
print(result)  # True

将字符串转换为数字

可以用int()转换成整型,用float()转换成浮点型

Str = '3,5.2'
sStr1, sStr2 = Str.split(',')
result = int(sStr1)
print(result)  # 3
result = float(sStr2)
print(result)  # 5.2

 

参考:https://blog.youkuaiyun.com/yl2isoft/article/details/52079960

           https://www.jianshu.com/p/b758332c44bb

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值