Python随笔-字符串

  • 函数title、lower、upper。
ct = "hello WORLD"
print(ct.title())    #title 以首字母大写的方式显示每个单词
print(ct.lower())
print(ct.upper())
# 结果:
# Hello World
# hello world
# HELLO WORLD
  • python 用+拼接字符串。
ct = "hello WORLD"
s = ct + "!"
print(s)
# 结果:
# hello WORLD!
  • 删除两侧空白strip。
s1 = '    s1 hello world           '
s2 = "!!!!!!!!!s2 hello world!!!!!!!!!!!!"
#删除字符串右边的字符,默认为空白
print(s1.rstrip() + "|")
print(s2.rstrip("!") + "|")
#删除字符串左边的字符,默认为空白
print(s1.lstrip() + "|")
print(s2.lstrip("!") + "|")
#删除字符串两边的字符,默认为空白
print(s1.strip() + "|")
print(s2.strip("!") + "|")
# 结果:
#     s1 hello world|
# !!!!!!!!!s2 hello world|
# s1 hello world           |
# s2 hello world!!!!!!!!!!!!|
# s1 hello world|
# s2 hello world|
  •  字符串运算符
+ 字符串连接

>>>a+b

'HelloPython'

* 重复输出字符串

 >>>a*2

"HelloHello"

in 成员运算符-如果字符串中包含给定的字符返回True

>>>"H" in a

True

r/R 原始字符串,不进行转义

>>>print(r" hh")

hh

  • python支持用三引号表达复杂的字符串
# python三引号允许一个字符串跨多行,字符串中可以包含换行符、制表符以及其他特殊字符。
ss = '''
line1
line2
line3
'''
print(ss)
原文地址:https://www.cnblogs.com/wrbxdj/p/9377675.html