python中的字符转运算符、字符串处理方式

 更新时间:2022年07月15日 10:16:33   作者:s651665496  
这篇文章主要介绍了python中的字符转运算符、字符串处理方式,具有很好的参考价值,希望对大家有所帮助。如有错误或未考虑完全的地方,望不吝赐教
(福利推荐:【腾讯云】服务器最新限时优惠活动,云服务器1核2G仅99元/年、2核4G仅768元/3年,立即抢购>>>:9i0i.cn/qcloud

(福利推荐:你还在原价购买阿里云服务器?现在阿里云0.8折限时抢购活动来啦!4核8G企业云服务器仅2998元/3年,立即抢购>>>:9i0i.cn/aliyun

字符转运算符、字符串处理

def CalSingleVals(val1, val2):
    op = ['+', '-', '*', '/']
    rtValList = []
 
    for op1 in op:
        st = str(val1) + op1 + str(val2)
        result = int(eval(st))

默认用法:去除空格

  • str.strip():去除字符串两边的空格
  • str.lstrip():去除字符串左边的空格
  • str.rstrip():去除字符串右边的空格
def trim(s):
... ? ? import re
... ? ? if s.startswith(' ') or s.endswith(' '):
... ? ? ? ? return re.sub(r"^(\s+)|(\s+)$", "", s)
... ? ? return s

字符串支持的运算符及使用

python中字符串支持哪些运算符呢?

在python中,字符串可以使用以下运算符:

+
*
in
not in
is
is not
==
!=

使用方法举例

‘+’ 运算符,拼接字符串的作用

s1 = 'hello'
s2 = 'world'
print(s1+s2)

运行结果:

‘*’ 运算符,字符串的倍数

s1 = 'a' * 5
print(s1)

运行结果:

in 运算符,判断是否在字符串中,返回布尔类型 True或False

s1 = 'hello world!'
result = 'w' in s1
print(result)

运行结果:

not in 运算符,判断是否不在字符串,返回布尔类型 False或True

s1 = 'hello world!'
result = 'w' not in s1
print(result)

运行结果:

is 运算符,判断字符串地址是否相同,返回布尔类型 True或False

s1 = 'hello world!'
s2 = 'hello world!'
result = s1 is s2
print(result)

运行结果:

is not 运算符,判断字符串地址是否相同,返回布尔类型 False或True

s1 = 'hello world!'
s2 = 'hello world!'
result = s1 is not s2
print(result)

运行结果:

== 运算符,判断字符串是否相等,返回布尔类型 True或False

s1 = 'hello world!'
s2 = 'hello world!'
result = s1 == s2
print(result)

运行结果:

!= 运算符,判断字符串是否相等,返回布尔类型 False或True

s1 = 'hello world!'
s2 = 'hello world!'
result = s1 != s2
print(result)

运行结果:

以上为个人经验,希望能给大家一个参考,也希望大家多多支持程序员之家。

相关文章

最新评论

?


http://www.vxiaotou.com