本文共 1642 字,大约阅读时间需要 5 分钟。
初学Python时,字符串操作可能会让人感到困惑,但理解这些基本概念后,处理文本数据会变得更加高效。以下是一些关键点和示例,帮助你更好地掌握Python字符串操作。
s = 'abcd's1 = s[0] # 输出 'a'
s = 'abcd's2 = s[0:3] # 输出 'abc',不包括索引3的字符s3 = s[-1] # 输出 'd'
s = 'abcd's4 = s[0:] # 输出 'abcd's5 = s[:] # 输出 'abcd's6 = s[0:0] # 输出空字符串
s = 'abcde's6 = s[0:4:2] # 输出 'ac'
s = 'abcde's7 = s[-1::-1] # 输出 'edcba'
s = 'AbCd's.swapcase() # 输出 'aBcD'
s = 'AAA's1 = s.center(20) # 居中,总长度为20s2 = s.center(20, '*') # 居中,填充字符为*
s = 'ab\tcd's1 = s.expandtabs() # 输出 'ab cd'
s = 'abcd我'print(len(s)) # 输出5
s = 'abcd's1 = s.startswith('a') # Trues2 = s.startswith('ab') # Trues3 = s.startswith('abc') # Trues4 = s.endswith() # 判断是否以空字符串结尾,默认返回False s = 'abcdacd's1 = s.find('c') # 输出2 s = ' abcd 's.strip() # 输出 'abcd's.strip('*') # 输出 'abcd's.strip(' %*') # 输出 'abcd' s = 'abbcd's.count('a') # 输出1s.count('bb') # 输出1 s = 'a b c d's.split() # 输出 ['a', 'b', 'c', 'd']s.split(';') # 输出 ['', 'a', 'b', 'c', 'd'] s = '我叫{},今年{}'.format('sun', '19') # 输出 '我叫sun,今年19's = '我叫{0},今年{1}'.format('sun', '19') # 输出 '我叫sun,今年19's = '我叫{name},今年{age}'.format(age=19, name='sun') # 输出 '我叫sun,今年19' s = 'abacda's.replace('a', 'A') # 输出 'ABacda's.replace('a', 'A', 1) # 输出 'ABacda' s = '123's.isnum() # Trues.isalpha() # Falses.isalnum() # True
s = 'abcd'for i in s: print(i)
s = 'abcdacd'i = 0while i < len(s): print(s[i]) i += 1
s = 'azxczcx政治'if '政治' in s: print('含有敏感词') 通过这些示例,你可以开始在Python中灵活使用字符串操作,处理各种文本数据问题。
转载地址:http://opofz.baihongyu.com/