python中用什么函数读取字符串_Python(2)字符串的主要方法

二、字符串方法

1. 获取字符串的长度,使用函数len()

1 a = "Hello, World!"

2 print(len(a))

2. 删除字符串前后空格,使用函数strip()

1 a = "Hello, World!"

2 print(a.strip())

说明: 如果只删除左边的空格,使用函数lstrip(); 如果只删除右边的空格,使用rstrip()

3. 返回大写的字符串,使用upper()

1 a = "Hello, World!"

2 print(a.upper())

4. 返回小写的字符串,使用lower()

1 a = "Hello, World!"

2 print(a.lower())

5. 用一个字符串,替换另一个字符串,使用函数replace()

1 a = "Hello, World!"

2 print(a.replace("World", "Kathy"))

6. 分割一个字符串,将字符串中的一个字符作为分隔符,使用函数split()

1 a = "Hello, World!"

2 print(a.split(","))

说明:这个函数返回的结果是列表

['Hello', ' World!']

7. 返回指定值在字符串中出现的次数,使用函数count()

1 txt = "I love apples, apple are my favorite fruit"

2 x = txt.count("apple")3 print(x)

8. 使用指定的编码对字符串进行编码,默认的编码为‘utf-8’。编码使用函数encode()

1 txt = "My name is Kathy."

2 x =txt.encode(encoding='ascii')3 print(x)

9. 函数string.starts(value, start, end), 判断字符串是否以给定值开始,可定义字符串从哪个位置开始判断,并哪个位置结束判断,后两个参数可省略。函数返回布尔值。

1 txt = "Hello, welcome to my world."

2 x = txt.startswith("Hello") #判断字符串txt是否以Hello开头

3 print(x)4

5 txt = "Hello, welcome to my world."

6 x = txt.startswith("wel", 7, 20) #判断字符串txt的第7个字符到20个字符是否以wel开头

7 print(x)

说明:这个方法相类似的还有 string.endswith() 判断字符串是否以给定值结尾

10. 函数string.find(value, start, end), 在字符串中搜索给定的值,返回首次出现的位置,如果找不到,则返回-1. 该方法和string.index()相似,只不过后者如果没有找到将发生异常。

1 txt = "Hello, welcome to my world."

2 x = txt.find("welcome")3 print(x)

11. 函数string.isalnum(),判断字符串是否都是字母数字,返回布尔值。类似的方法还有:isalpha(), isdecimal(), isdigit(), islower(), isupper(), isnumeric(), isidentifier(), isspace(),

1 txt = "Company12"

2 x =txt.isalnum()3 print(x)

参考资料:

http://python.org

https://www.w3school.com.cn

https://www.runoob.com

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值