python stringstrip方法详解_Python 基础知识全篇-字符串(Strings)

字符串是字符的集合。

单引号和双引号

字符串可以包含在单引号或双引号中。

my_string = "This is a double-quoted string."

my_string = 'This is a single-quoted string.'

这种灵活的方式可以让我们在字符串中包含引号。

quote = "Linus Torvalds once said, 'Any program is only as good as it is useful.'"

多行字符串

当我们需要创建一个多行字符串的时候,可以用三个引号。如下所示:

multiline_string = '''This is a string where I

can confortably write on multiple lines

without worring about to use the escape character "\\" as in

the previsou example.

As you'll see, the original string formatting is preserved.

'''

print(multiline_string)

改变大小写

你可以很方便的改变字符串的大小写。如下所示:

first_name = 'eric'

print(first_name)

print(first_name.title())

最常见的大小写形式是全小写(lower),首字母大写(title)和全大写(upper)。如下所示:

first_name = 'eric'

print(first_name)

print(first_name.title())

print(first_name.upper())

first_name_titled = 'Eric'

print(first_name_titled.lower())

注意:初始字符串没被改变。

print(first_name)

print(first_name_titled)

你会经常见到这种用法。变量名后跟点和操作名称,且后跟一组圆括号。圆括号里可能是空的,也可能包含一些数据。

variable_name.action()

在这个例子中,action 是一个方法的名字。title, lower, upper 是内置在 Python 中的函数,可以作用于字符串的方法。

连接字符串

字符串连接示例如下所示:

first_name = 'ada'

last_name = 'lovelace'

full_name = first_name + ' ' + last_name

print(full_name.title())

加号连接两个字符串。你可以使用任意个加号来连接字符串。

first_name = 'ada'

last_name = 'lovelace'

full_name = first_name + ' ' + last_name

message = full_name.title() + ' ' + \

"was considered the world's first computer programmer."

print(message)

格式化字符串简介

string_template = 'The result of the calculation of {calc} is {res}'

print("String Template: ", string_template)

print(string_template.format(calc='(3*4)+2', res=(3*4)+2))

空白符

空白符通常指计算机能够发现但不可见的字符。诸如空格,制表符,换行符等。

空格很容易创建,基本上在你拥有计算机的时候就会打出空格符。制表符和换行符是由特殊字符连接组成的。

"\t" 代表制表符,"\n" 代表换行符。你可以将它们添加进字符串的任意部分。

print("\tHello everyone!")

print("Hello \teveryone!")

print("\nHello everyone!")

print("\n\n\nHello everyone!")

去除空白符

有时候我们想去除掉字符串开始或者结尾的空白符。Python 中有一些方法可以帮我们做到这点。如下所示:

name = ' eric '

print(name.lstrip())

print(name.rstrip())

print(name.strip())

lstrip 去除左侧开端的空白符,rstrip 去除右端结尾的空白符,strip 去除两端空白符。

看一个更清晰的例子,如下所示:

name = ' eric '

print('-' + name.lstrip() + '-')

print('-' + name.rstrip() + '-')

print('-' + name.strip() + '-')

动手试一试

Someone Said找一条自己喜欢的名言,存储在变量。结合适当的介绍打印出来。例如:"Ken Thompson once said, 'One of my most productive days was throwing away 1000 lines of code'"。

First Name Cases将你的姓存储在一个变量中。

分别用 lowercase, Titlecase, UPPERCASE 三种方式打印姓。

Full Name将你的名和姓存储在不同的变量中,连接它们并打印。

Name Strip将你的姓存储在变量中。在姓的前后两端至少各包含两种空白符。

打印姓。

分别打印出去掉左侧空白符,右侧空白符,都去掉空白符的姓。

# Ex : Someone Said

# put your code here

# Ex : First Name Cases

# put your code here

# Ex : Full Name

# put your code here

# Ex : Name Strip

# put your code here

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值