小白学Python—Day09

1.字符串操作

  ①重复输出字符串

  print("hello" * 2)

  ②切片操作,与列表相同

  print("hello" [1:])

  ③in 判断元素是否在字符串里,与列表相同

  print("e" in "hello")

  ④格式化输出

  name = "kathrine"

  print("%s is a good boy" % name)

  ⑤字符串拼接,不建议使用。

2.字符串内置方法

  ①join方法,字符串拼接,join前是一个字符串或空的字符串,添加的内容是列表或者元组格式。

  d = "000".join(["a","b"])

  ②.count方法,字符串中某一元素的个数。

  print("hello".count("l"))

  ③.capitalize 把字符串首字母大写

  print("hello".capitalize())

  ④..center (字符总个数,"居中内容除外的其他内容"),居中

  print("hello".center(50,"-"))

  ⑤.startswith,判断是否以某个元素为开始,可以是范围,会返回布尔值。

  print("hello".startswith("he"))

  ⑥在字符串上加入\t(表示制表符),可以用.expandtabs设定制表符的空格个数。

  print("he\tllo".expandtabs(5))

  ⑦.find查找字符串中某一个元素的索引值,并返回索引值,如不存在此元素,会返回-1.

  print("hello".find("h"))

  ⑧.format/.format_map格式化输出的另一种方式

  format方法

  通过参数在format方法中的位置实现格式化输出。

  name = "my name is {0},my age is {1}-{0}"

  val = name.format ("kathrine",20)

  print(val)

  format括号后的参数如果是列表,要加*

  name = "my name is {0},my age is {1}-{0}"

  val = name.format ( * ["kathrine",20])

  print(val)

  format后的参数可以是变量直接赋值的方法

  nAme = input(">>:")

  info = "my name is {name},age is {age}"

  val = info.format(name = nAme , age =18 )

  print(val)

  format参数是字典的情况,用两个**

  name = "我叫{name},年龄{age}"

  dic = {'name':'kathrine','age':18}

  val = name.format(**dic)

  print(val)

  format_map方法,参数必须是一个字典

  info = "my name is {name},age is {age}"

  dic = {"name":"kathrine","age":19}

  val = info.format_map(dic)

  print(val)

  注:字典会在后续的随笔中体现。

  ⑨index 字符串某一个元素的索引值,如不包括这一元素,会报错

  print("hello".index("h"))

  ⑩isalnum判断字符串是否包含字母或数字,如果包含空格或特殊字符会返回错误值

  print("hello12345".isalnum())

  11.isdecimal判断是否是十进制

  print("hello123".isdecimal())

  12检测字符串是否只由字母组成

  print("h123".isalpha())

  13判断字符串是否是一个整型数字

  print("123.111".isdigit())

  print("123.11".isnumeric())

  14判断是否是非法变量

  print("123ggg'.isdentifier())

  15检验字母是否全部为小写

  print("123ggg'.islower())

  16检验字母是否全部为大写

  print("123ggg'.isupper())

  17检验是否是一个空格

  print( " ".isspace())

  18判断是否是标题,标题的特征是每个单词首字母大写

  print("Abc Def".is title())

  print("abc Def".is title())

  19字符串中所有大写变小写

  print("abcQW12".lower())

  20字符串中所有小写变大写

  print("abcQW12"。upper())

  21与center类似,不过是字符串在左边

  print("hello".ljust(50,"*"))

  22与center类似,不过是字符串在右边

  print("hello".rjust(50,"*"))

  23去掉字符串前后换行符空格和制表符

  .strip把字符串前后换行符和空格和制表符去掉(\n是换行符)
   .lstrip把字符串左边换行符和空格和制表符去掉(\n是换行符)
   .rstrip把字符串右边换行符和空格和制表符去掉(\n是换行符)

  print(" abc Def ".strip())

  print(" abc Def\n ".strip())

  24替换内容,.replace("要被替换的内容",“需要的内容”,替换几个值)

  print("hello".replace("h","f",1))

  25真实的索引位置

  print("hello".rfind("e"))

  26把字符串拆分成列表,以字符串中某个元素为分隔对象,分隔对象不会被输出

  print("ab cdef".split(" ")) 从空格拆分

  print("ab cdef".split("b")) 从b拆分

  27从右往左拆分rsplit("从哪里分",分几次)

  print("abc bws webs".rsplit("b",1))

  28把字符串变成标题格式

  print('abc bef.title()')

  

猜你喜欢

转载自www.cnblogs.com/Kathrine/p/11955663.html