• 技术文章 >Python技术 >Python基础教程

    有用的20个python代码段(1)

    尤及尤及2020-06-13 17:00:09转载1782

    有用的20个python代码段(1):

    1、反转字符串

    以下代码使用Python切片操作来反转字符串。

    # Reversing a string using slicing
    my_string = "ABCDE"
    reversed_string = my_string[::-1]
    print(reversed_string)
    # Output
    # EDCBA

    2、使用标题类(首字母大写)

    以下代码可用于将字符串转换为标题类。这是通过使用字符串类中的title()方法来完成。

    my_string = "my name is chaitanya baweja"
    # using the title() function of string class
    new_string = my_string.title()
    print(new_string)
    # Output
    # My Name Is Chaitanya Baweja

    3、查找字符串的唯一要素

    以下代码可用于查找字符串中所有的唯一要素。我们使用其属性,其中一套字符串中的所有要素都是唯一的。

    my_string = "aavvccccddddeee"
    # converting the string to a set
    temp_set = set(my_string)
    # stitching set into a string using join
    new_string = ''.join(temp_set)
    print(new_string)

    4、输出 n次字符串或列表

    你可以对字符串或列表使用乘法(*)。如此一来,可以按照需求将它们任意倍增。

    n = 3 # number of repetitions
    my_string = "abcd"
    my_list = [1,2,3]
    print(my_string*n)
    # abcdabcdabcd
    print(my_list*n)
    # [1,2,3,1,2,3,1,2,3]
    import streamlit as st
    一个有趣的用例是定义一个具有恒定值的列表,假设为零。
    n = 4
    my_list = [0]*n # n denotes the length of the required list
    # [0, 0, 0, 0]

    更多Python知识,请关注:Python自学网!!

    专题推荐:python
    品易云
    上一篇:Python 字符串操作常用知识点(1) 下一篇:Python中的56个内置函数详解(一)

    相关文章推荐

    • python存储jpg图片出错解决方法• python程序出错删除一行代码怎么做• python代码检测工具及区别• python如何提取矩阵第二列• python代码用什么看• python怎么将字符串用空格分开• python导入dlib时出错解决方法• 怎样查看python环境是否安装正确

    全部评论我要评论

    © 2021 Python学习网 苏ICP备2021003149号-1

  • 取消发布评论
  • 

    Python学习网