zoukankan      html  css  js  c++  java
  • 4.入门字符串练习

    1 #for 循环遍历一个字符串排除一些条件并获得一个新字符串
    先设一个空字符串 再依次累加到空字符串中去得到结果。

    C=''
    str=input('请输入一个字符串:')
    for i in range(0,len(str)):
    if str[i].isdigit()==False:
    C=C+str[i]
    i+=1

    2#统计字符串出现的每个字母的出现次数(忽略大小写),并输出成一个字典
    A={}
    for i in C.upper():
    if A.get(i)==None:
    A[i]=1
    else:
    A[i]+=1
    for k,v in A.items():
    print('%s的个数为:%s'%(k,v))
    print(A)

    3#去除字符串中多次出现的字母(忽略大小写),并统计新字符串
    思路:需要先把字符串大小写转为一致,再遍历加入到新列表里面
    如果没有则添加进去避免重复

    list=[]
    B=''
    for i in C.upper():
    if i not in list:
    list.append(i)
    print('新字符串:%s'%B.join(list)

    ——————————————————————————————————————————

    1 #检查字符串的开头和结尾

    # info='我有两把枪'
    # ret=info.startswith('我')
    # print(ret)
    # info='我有两把枪'
    # ret=info.endsswith('枪')
    # print(ret)

    2 #所有字符串都是数字或是字母

    # info='123股票'
    # ret=info.isalnum()
    # print(ret)

    3 #所有字符串都是字母

    # info='qwer'
    # ret=info.isalpha()
    # print(ret)

    4 #、所有字符串都是数字

    # info='123456'
    # ret=info.isdigit()
    # print(ret)

    5 #所有字符串都是大写

    # info='123AB'
    # ret=info.isupper()
    # print(ret)

    6 #所有字符串都是大写

    # info='123AB'
    # ret=info.islower()
    # print(ret)

    7 #只包含空格返回True

    # info=' '
    # ret=info.isspace()
    # print(ret)

    8 #字符串第一个字母大写

    info='abcA'
    ret=info.capitalize()
    print(info)
    print(ret)


    9 #字符串第一个字母大写

    info='abcA'
    ret=info.capitalize()
    print(info)
    print(ret)

    10 #转换info中的小写字母大写

    info='abcA'
    ret=info.upper()
    print(info)
    print(ret)

    11 #转换info中的大写字母小写

    info='abcA'
    ret=info.lower()
    print(info)
    print(ret)

    12 #居中,左对齐,右对齐

    info='a123456'
    ret=info.ljust(10)
    print(ret)
    info='a123456'
    ret=info.rjust(10)
    print(ret)
    info='a123456'
    ret=info.center(11,'*')
    print(ret)

    13 #删除字符串 前后 左,右 字符

    info='123456123'
    ret=info.strip('123')
    print(ret)

    info='123456123'
    ret=info.lstrip('123')
    print(ret)

    info='123456123'
    ret=info.rstrip('123')
    print(ret)

    14 #合并
    ret=['我','的','剑']
    info='**'
    ret2=info.join(ret)
    print(ret2)

    15

  • 相关阅读:
    返回一个整数数组中最大子数组的和
    对autocad的建议
    作业:30道四则运算——C++编程
    四则运算2
    [leetcode] Letter Combinations of a Phone Number
    [leetcode] Pow(x, n)
    [leetcode] Longest Common Prefix
    [leetcode] Binary Tree Zigzag Level Order Traversal
    [leetcode] Construct Binary Tree from Preorder and Inorder Traversal
    [leetcode] Construct Binary Tree from Inorder and Postorder Traversal
  • 原文地址:https://www.cnblogs.com/lvjing/p/9524725.html
Copyright © 2011-2022 走看看