人话学Python-基础篇-字符串

        一:字符串的定义

        在Python中使用引号来定义。不论是单引号还是双引号。

str1 = 'Hello World'
str2 = "Hello World"

        二:字符串的访问

        如果我们要取出字符串中单独的字符,需要使用方括号来表示取得的位置。如果要取出字符串的子串,就需要用到冒号表达式

        str[a:b]

        上面的冒号表达式意为从字符串的第a+1位取到第b位

        需要注意的是,和大部分编程语言一样,Python也是从0开始计数。

str = "Hello World"

print("the first string of str is", str[0])
print("the second string of str is", str[1])

print("the first four string of str is", str[0:4])

#>>>the first string of str is H
#>>>the second string of str is e
#>>>the first four string of str is Hell

        使用冒号表达式,可以实现指定位置的字符串替换

str = "Hello World"

print("The new string is", str[:6] + "Bye Bye")

#>>>The new string is Hello Bye Bye

        三:字符串的运算

+ 字符串连接
* 字符串重复输出
in

成员运算符

如果字符串包含给定字符返回1

not in

成员运算符

如果字符串不包含给定字符返回1

% 格式字符串
str1 = "Hello"
str2 = "World"

print(str1 + str2)
print(str1*2,str2*3)

print("H" in str1)
print("a" not in str2)

#>>>HelloWorld
#>>>HelloHello WorldWorldWorld
#>>>True
#>>>True

        四:格式字符串     

        格式字符串是一种C语言风格的字符串表示方法,使用%作为标志。

%c 格式化字符及ASCII码
%s 格式化字符串
%d 格式化整数
%f 格式化浮点数,可指定精确度
print("My name is %s , I'm %d years old" % ("Jujube" , 19))

#>>>My name is Jujube , I'm 19 years old

        在使用格式化字符串时,有辅助指令可以帮助具体操作。

* 定义小数点精度
- 左对齐
+ 在正数前面显示正号
<sp> 在正数前面显示空格
0 显示的数字前面填充0而不是默认的空格

五:format()函数

        format()函数通过{}和:代替%。运用更加灵活。

print("{} {}".format("Hello", "World"))

print("{1} {0}".format("Hello", "World"))

print("{0} {1} {0}".format("Hello", "World"))

#>>>Hello World
#>>>World Hello
#>>>Hello World Hello

        也可以在字符串中添加变量

print("{name}'s score is {points}".format(name="Jujube", points="90"))

#>>>Jujube's score is 90

相关推荐

  1. Python 千题 —— 基础字符串拼接

    2024-07-10 05:34:01       42 阅读
  2. 基础Python的第六天||字符串(3)

    2024-07-10 05:34:01       45 阅读
  3. Python基础-字符串

    2024-07-10 05:34:01       38 阅读

最近更新

  1. docker php8.1+nginx base 镜像 dockerfile 配置

    2024-07-10 05:34:01       3 阅读
  2. Could not load dynamic library ‘cudart64_100.dll‘

    2024-07-10 05:34:01       4 阅读
  3. 在Django里面运行非项目文件

    2024-07-10 05:34:01       2 阅读
  4. Python语言-面向对象

    2024-07-10 05:34:01       2 阅读

热门阅读

  1. MySQL 中 SQL 查询语句的执行顺序

    2024-07-10 05:34:01       13 阅读
  2. Python之MoviePy视频编辑模块介绍与应用

    2024-07-10 05:34:01       13 阅读
  3. 对Mapper.xml文件进行深入的学习

    2024-07-10 05:34:01       13 阅读
  4. 工作中遇到的问题与解决办法(三)

    2024-07-10 05:34:01       9 阅读
  5. linux工具应用_VERDI

    2024-07-10 05:34:01       11 阅读
  6. 大模型/NLP/算法面试题总结4——bert参数量计算

    2024-07-10 05:34:01       13 阅读
  7. springsecurity(学习自用)

    2024-07-10 05:34:01       10 阅读
  8. 构建响应式CSS导航栏:实现优雅的用户体验

    2024-07-10 05:34:01       10 阅读
  9. debian或Ubuntu中开启ssh允许root远程ssh登录的方法

    2024-07-10 05:34:01       10 阅读
  10. 深入理解基本数据结构:链表详解

    2024-07-10 05:34:01       7 阅读
  11. 白骑士的C++教学基础篇 1.3 控制流

    2024-07-10 05:34:01       7 阅读