python学习1.2字符串

本文介绍了Python中字符串的基本操作,包括如何使用引号赋值,转换字符串的大小写,如何连接字符串以及利用f-string进行格式化输出。此外,还讲解了制表符和换行符的使用,以及如何删除字符串开头和末尾的空白。这些基础知识对于Python编程至关重要。
摘要由CSDN通过智能技术生成

一、给变量赋值字符串的时候,要用引号引起来,可以用单引号或者双引号;

1、输入:

message="hello world"
print(message)

输出:

hello world

2、输入:

message='hello world'
print(message)

输出:

hello world

注:这样可以方便的打印带引号的字符串;

3、输入:

message="cy said 'hello world'"
print(message)

输出:

cy said 'hello world'

4、输入:

message='cy said "hello world"'
print(message)

输出:

cy said "hello world"

二、修改字符串的大小写

(1). title() :把字符串中每个单词的首字母变为大写,其它置为小写

输入:

message='cy sAid "hello world"'
print(message.title())

输出:

Cy Said "Hello World"

注:message.title()中的.可以理解为要执行.后面的操作,而括号里则是一些附加的操作,不需要则为空;

(2).upper() : 把字符串全部变为大写

输入:

message='cy sAid "hello world"'
print(message.upper())

输出:

CY SAID "HELLO WORLD"

(3).lower() : 把字符串全部变为小写

输入:

message='cy sAid "hello world"'
print(message.lower())

输出:

cy said "hello world"

 三、连接字符串:使用f"{ a }{ b }"

1、变量用 { } 括起来

输入:

first_string="hello"
second_string="world"
fina_string=f"{first_string}{second_string}"
print(fina_string)

输出:

helloworld

 2、{ }之外的字符也会起作用,可以穿插在{ }{ }之间,包括空格

输入:

first_string="hello"
second_string="world"
fina_string=f"Cy said {first_string} {second_string}"
print(fina_string)

输出:

Cy said hello world

四、制表符(\t)和换行符(\n)的妙用

输入:

print("Language:\n\tPython\n\tC\n\tJavascript")

输出:

Language:
	Python
	C
	Javascript

五、删除字符串中的空白:Python 能够找出字符串开头和末尾多余的空白;

1、要确保字符串末尾没有空白,可使用.rstrip();

first_string="Python "
print(first_string.rstrip())

注:这种操作删除空白只是暂时的,要关系到变量才是永久的,一般这样做

first_string="Python "
first_string=first_string.rstrip()
print(first_string)

2、要确保字符串开头没有空白,可使用.lstrip();

first_string=" Python"
first_string=first_string.lstrip()
print(first_string)

 3、要确保字符串开头没有空白,可使用.strip();

first_string=" Python "
first_string=first_string.strip()
print(first_string)

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值