您的位置:

Python字符串函数的用法详解

一、Python string函数用法

在Python中,字符串是指由一系列字符组成的序列,Python string函数用于处理字符串类型。

Python string函数包括以下用法:

string.capitalize()  # 把字符串的第一个字符大写
string.casefold() # 把字符串全部转换为小写
string.center(width[, fillchar]) # 返回一个指定宽度的字符串,原字符串居中,用指定字符或空格填充
string.count(sub[, start[, end]]) # 返回字符串中包含子字符串的个数

以string.capitalize()为例进行演示:

# 先定义一个字符串
str = "hello world!"
# 输出结果为:Hello world!
print(str.capitalize())

该代码会输出"Hello world!",因为string.capitalize()会把字符串的第一个字符大写。

二、Python print函数

Python中的print函数用于输出信息到控制台。

使用Python print函数将结果输出:

str1 = "hello"
str2 = "world"
# 输出结果为:hello world
print(str1, str2)

使用Python print函数强制换行:

str = "hello world!"
# 输出结果为
# hello
# world!
print(str, end="\n\n")

其中,end="\n\n"表示输出后换两个新行。

三、Python的string函数

Python string函数还包括以下用法:

string.encode(encoding='UTF-8',errors='strict')  # 将字符串转换为指定编码;
string.endswith(suffix[, start[, end]]) # 测试字符串是否以指定的后缀结尾,返回 True 或 False;
string.expandtabs(tabsize=8) # 把字符串中的 tab 符号 (\t) 转换为空格,tabsize 指定转换的空格数,默认为 8;
string.find(sub[, start[, end]]) # 搜索字符串中指定的子字符串并返回起始索引,如果没有匹配返回 -1;

以string.encode()为例进行演示:

str = "Python, 真是个不错的编程语言!"
# 输出结果为:b'Python, \\xe7\\x9c\\x9f\\xe6\\x98\\xaf\\xe4\\xb8\\xaa\\xe4\\xb8\\x8d\\xe9\\x94\\x99\\xe7\\x9a\\x84\\xe7\\xbc\\x96\\xe7\\xa8\\x8b\\xe8\\xaf\\xad\\xe8\\xa8\\x80!'
print(str.encode())

四、Python函数大全及使用

Python提供了大量的函数,在这里我们仅列举其中几个常用的函数:

int(x [,base])  # 将一个字符串/数字/浮点数转换为整数;
title() # 返回 "标题化" 的字符串,就是说所有单词都是以大写开始,其余字母均小写;
isdigit() # 如果字符串只包含数字,则返回 True,否则返回 False;

以int()函数为例进行演示:

str = "123456"
# 输出结果为:123456
print(int(str))

五、Python字符串函数

Python字符串函数还包括以下用法:

string.lstrip()  # 返回去掉左侧空格的字符串;
string.join(sequence) # 连接序列中的元素以构造一个新的字符串;
string.partition(sub) # 查找子字符串,返回一个3元组,包含第一个出现位置之前的字符、子字符串、第一个出现位置之后的字符;
string.replace(old, new[, count]) # 返回一个字符串,在这个字符串中将字符串old替换为new,如果指定第3个参数则替换不超过count次。

以string.lstrip()为例进行演示:

str = "   hello world!"
# 输出结果为:hello world!
print(str.lstrip())

六、Python count函数

Python count函数用于返回字符串中指定子串出现的次数。

示例代码:

str = "this is a dog"
# 输出结果为:1
print(str.count("dog"))

七、Python函数int

Python函数int接受数字字符串并将其转换为整数。

示例代码:

str = "123"
# 输出结果为:123
print(int(str))

八、Python函数title

Python函数title用于将所有单词的首字母大写。

示例代码:

str = "this is a dog"
# 输出结果为:This Is A Dog
print(str.title())

九、Python的string函数

Python的string函数还包括以下用法:

string.strip([chars])  # 在字符串的开头和结尾删除空白字符(包括换行符、制表符等);
string.swapcase() # 返回大小写字母互换后的字符串;
string.startswith(obj, beg=0,end=len(string)) # 检查字符串是否是以obj开始,是的话返回 True,否则返回 False;
string.upper() # 将字符串中的小写字母转换为大写字母;

以string.strip()为例进行演示:

str="   hello world!   "
# 输出结果为:hello world!
print(str.strip())

总结

本文详细介绍了Python字符串函数的用法,涉及Python的string函数、print函数、count函数、title函数等,希望对初学者有所帮助。