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+bpython

'HelloPython'函数

* 重复输出字符串

 >>>a*2spa

"HelloHello"code

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

>>>"H" in ablog

Trueip

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

>>>print(r"\nhh")字符串

\nhhit

 

 

 

 

 

 

 

 

 

  • python支持用三引号表达复杂的字符串
# python三引号容许一个字符串跨多行,字符串中能够包含换行符、制表符以及其余特殊字符。
ss = '''
line1
line2
line3
'''
print(ss)
相关文章
相关标签/搜索