字符串基础
- ""
- Python文本之一[字符串基础]
- Python version: 3.4
- """
- #单引号
- str_single_quotes = 'blog: http://www.csdn.net/wirelessqa'
- #双引号
- str_double_quotes = "blog: http://www.csdn.net/wirelessqa"
- print ("## 单引号: " + str_single_quotes)
- print ("## 双引号: " + str_double_quotes)
- #用\分行
- str_multi_line = "blog:\
- http://www.csdn.net/wirelessqa"
- print ("## 使用\\分行: " + str_multi_line)
- #用\n换行显示
- str_n = "blog:\nhttp://www.csdn.net/wirelessqa"
- print ("## 使用\\n换行: " + str_n)
- #三引号"""显示多行
- str_more_quotes = """
- my
- name
- is
- Mr.B
- """
- print ("## 使用三引号\"\"\"n显示多行: " + str_more_quotes)
- #用r或R显示原貌
- str_r = r"我是\
- 帅哥"
- str_R = R"我是\n帅哥"
- print ("## 用r显示原貌: " + str_r)
- print ("## 用R显示原貌: " + str_R)
- #使用u或U使之成为Unicode字符串
- str_u = u'老\u0020毕'
- print ("## 使用u或U使之成为Unicode字符串: " + str_u)
- #注意: 字符串是无法改变的,无论你对它做什么操作,你总是创建了一个新的字符串对象,而不是改变了原有的字符串
- #
- #字符串是字符的序列,所以也可以通过索引的方法访问单个字符
- test_str_index = "我是帅哥"
- print ("## index 0: " + test_str_index[0])
- print ("## index -1: " + test_str_index[-1])
- #使用切片访问字任串的一部分
- print ("## [0:3]: " + test_str_index[0:3])
- print ("## [2:]: " + test_str_index[2:])
- print ("## [-1:]: " + test_str_index[-1:])
- print ("## 遍历整个字符串: ")
- for t in test_str_index:print (t)
- #构建另一个序列
- str_list = list(test_str_index) #['我', '是', '帅', '哥']
- #字符串拼接
- str_add = test_str_index + '哈哈'
- print ("## 字符串拼接" + str_add)
- print("## 使用乘法对字符串多次重复: " + '老毕' * 3)
- #使用s.isdigit()来判断字符串是否全为数字
- test_isdigit_true = '782670627'
- test_isdigit_false = 'abcd123'
- test_isdigit_empty = ''
- if test_isdigit_true.isdigit():
- print (test_isdigit_true + " 字符串都是数字")
- if not test_isdigit_false.isdigit():
- print (test_isdigit_false + " 字符串不都是数字")
- if not test_isdigit_empty.isdigit():
- print ("字符串为空")
- if len(test_isdigit_empty) == 0:
- print ("字符串为空")
- #将字符串转换成大写
- test_upper = test_isdigit_false.upper()
- print(test_upper)
- #将字符串转换成小写
- test_lower = test_upper.lower()
- print(test_lower)
- #测试某个字符在字符串中出现的次数
- test_count = "my name is my name"
- print ("## 测试某个字符在字符串中出现的次数: "+ str(test_count.count("name")))
- #使用s.splitlines()将一个有多行文本的字符串分隔成多行字符串并入一个列表中
- one_large_str = "chu he ri dang wu, \n han di he xia tu"
- list_lines = one_large_str.splitlines() #['chu he ri dang wu, ', ' han di he xia tu']
- print (list_lines)
- #使用'\n'.join()重新生成一个庞大的单字符串
- one_large_str2 = '\n'.join(list_lines)
- print (one_large_str2)
每次处理一个字符
- """
- Python3.4【文本】之每次处理一个字符
- """
- test_str = "my name is bixiaopeng"
- for x in range( 0, len(test_str)-1):
- print ("## 通过索引遍历字符串: " + test_str[x])
- for x in test_str:
- print ("## 直接遍历字符串: " + x)
- thelist = list(test_str)
- print (thelist) #['m', 'y', ' ', 'n', 'a', 'm', 'e', ' ', 'i', 's', ' ', 'b', 'i', 'x', 'i', 'a', 'o', 'p', 'e', 'n', 'g']
- for x in thelist:
- print ("## 遍历list: " + x)
- def printstr(a):
- print ("使用map遍历: " + a)
- list(map(printstr,test_str)) #注意: python3以后必须使用list来打印map的结果
- [print ("## 列表推导遍历: " + i) for i in test_str ]