python学习1.2字符串

2023-11-10

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

1、输入:

message="hello world"
print(message)

输出:

hello world

2、输入:

message='hello world'
print(message)

输出:

hello world

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

3、输入:

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

输出:

ww said 'hello world'

4、输入:

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

输出:

ww said "hello world"

二、修改字符串的大小写

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

输入:

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

输出:

Ww Said "Hello World"

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

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

输入:

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

输出:

WW SAID "HELLO WORLD"

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

输入:

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

输出:

ww 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"Ww said {first_string} {second_string}"
print(fina_string)

输出:

Ww 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)

本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)

python学习1.2字符串 的相关文章

  • 【k8s集群部署】使用docker作为运行时部署Kubernetes集群

    k8s集群部署 使用docker作为运行时部署Kubernetes集群 一 cri dockerd介绍 1 cri dockerd简介 2 cri dockerd代码托管地址 二 k8s集群环境规划 三 k8s集群环境准备工作 1 设置主机
  • 解惑好文:移动端H5页面高清多屏适配方案

    背景 开发移动端H5页面 面对不同分辨率的手机 面对不同屏幕尺寸的手机 视觉稿 在前端开发之前 视觉MM会给我们一个psd文件 称之为视觉稿 对于移动端开发而言 为了做到页面高清的效果 视觉稿的规范往往会遵循以下两点 1 首先 选取一款手机
  • uniapp canvas绘图

    问题描述 根据项目需求 将商品的图片 用户头像 二维码 商品信息绘制到分享海报中 效果展示 参数介绍 参数 类型 说明 avatarImg String 头像图片 bgImg String 背景图片 qrImg String 二维码 goo
  • java爬虫和python爬虫的区别

    java爬虫与python爬虫的对比 python做爬虫语法更简单 代码更简洁 java的语法比python严格 而且代码也更复杂 示例如下 url请求 java版的代码如下 public String call String url St
  • shell三剑客之grep 全局搜索工具 详解

    目录 grep 全局搜索工具 grep基本原理 grep语法结构 OPTION选项 PATTERN模式 正则表达式 grep实战 grep基本原理 gt gt gt grep全称global search regular expressio

随机推荐