专业编程基础技术教程

网站首页 > 基础教程 正文

Python快速入门系列3-Python中的常见数据类型-字符串

ccvgpt 2024-07-23 01:31:43 基础教程 10 ℃


编程语言最重要的是数据和算法,Python语言中常见的数据有数字、字符串、布尔型、列表、元组、集合和字典,其定义和增删改查的方法有哪些,还有什么特性?Python的标准库中不存在日期型(这个依赖另外的库datetime),下面我们先看看字符串

Python快速入门系列3-Python中的常见数据类型-字符串

(一)增加

str1="Hello,"

str2="world!"

result=str1+str2

print(result)#输出:Hello,world!

(二)删改

1、str.replace(old,new[,count]):将字符串中的old子串替换为new子串。

text="helloworld"

print(text.replace("world","Python"))#输出:"helloPython"

2、str.strip([chars]):移除字符串两端的空白字符或指定的chars字符。

text="helloworld"

print(text.strip())#输出:"helloworld"

(三)查找

1、顺查

text="helloworld!helloworld!"

print(text.find("world"))#输出:6

2、倒过来

text="helloworld!helloworld!"

print(text.rfind("world"))#输出:18

3、str.startswith(prefix[,start[,end]]):检查字符串是否以指定的前缀prefix开头。

text="helloworld"

print(text.startswith("hello"))#输出:True

4、str.endswith(suffix[,start[,end]]):检查字符串是否以指定的后缀suffix结尾。

text="helloworld"

print(text.endswith("world"))#输出:True

5、str.isalpha():检查字符串是否只包含字母。

text="hello"

print(text.isalpha())#输出:True

6、str.isdigit():检查字符串是否只包含数字。

text="12345"

print(text.isdigit())#输出:True

7、str.isalnum():检查字符串是否只包含字母和数字。

text="hello123"

print(text.isalnum())#输出:True

8、字符串的切片

(四)字符串与列表的转换

1、使用join() 方法合并字符串列表

words=["Hello","world"]

result="".join(words)

print(result)#输出:Helloworld

2、str.split(sep=None, maxsplit=-1): 通过指定分隔符sep对字符串进行分割。

text="helloworld"

print(text.split())#输出:['hello','world']

(五)字符串中如何嵌入变量

name="John"

age=30

result=f"{name} is {age} years old."

print(result)#输出:John is 30 years old.

最近发表
标签列表