search
HomeBackend DevelopmentPython TutorialTen Useful Python One-Linger Programs You Must Know

Ten Useful Python One-Linger Programs You Must Know

Although Python has gone through 30 years since its release, it remains one of the most relevant high-level programming languages ​​in existence. Many developers choose to use this language to develop applications that are easy to maintain and require little manual effort on many operating systems and Linux distributions.

One of the biggest benefits of Python is It's able to bypass (pun totally intended) many conventions in other languages, and with very little effort on the part of the programmer, it's possible to write very simple little "quips" that get the job done. Here are a few examples!

Content

  • 1. Swap variables
  • 2. Make a quick napkin factorial
  • 3. Initialize and declare multiple variables
  • 4. Open and read the file
  • 6. Create a list of number ranges
  • 7. Display all users (in Linux/Unix/BSD)
  • 8. Generate random passwords
  • 9. Find instances of anything in text
  • 10. Convert hexadecimal expressions to clear text
  • FAQ

1. Swap variables

Because you don’t have to deal with tedious things like addresses in memory, swapping between variables can be done in a single line of code:

x, y = y, x

Just use Comma separate each variable and swap them!

This is what this concept looks like in a snippet:

x = 1
y = 4
x, y = y, x
print(x,y)

Running this command in the console should output "4 1".

Ten Useful Python One-Linger Programs You Must Know

2. Make a quick napkin factorial

Python’s math tools allow some very creative code to perform complex calculations. For example, what is the fastest way to find out how some objects are arranged? Do the factorial. Call reduce() and you can figure out the answer quickly!

reduce(lambda a, b: a * b, range(1, x+1)

This call will calculate the factorial of any number you previously defined in "x"

Don't forget that reduce() is part of Python's function tools library. The code snippet looks like this:

from functools import reduce
x = 12print(reduce(lambda a, b: a * b, range(1, x+1)))

Your console should output 479001600 from this particular calculation. Keep doing "x" you want to do!

Ten Useful Python One-Linger Programs You Must Know

3. Initialize and declare multiple variables

Python's syntax rules allow you to do some pretty crazy things matter. For example, initialize and declare as many variables as possible at once. This is the opposite of executing line by line.

x, y, z = 16, 78, 195

Print these out and you'll get "16 78 195" The best part is, you don't even have to limit yourself to declaring a type of variable in one line. Replace the "y" statement with a string like "Hi" and you're good to go!

Ten Useful Python One-Linger Programs You Must Know

4. Open and read the file

Python requires you to iterate through the file line by line like in many other languages. Even so, it gives you the full functionality of opening and reading files in one line of code:

[line.strip() for line in open('file.txt')]

Now, if I just wanted to display the text of my own default bash profile, I would write like this :

[print(line.strip()) for line in open('/home/miguel/.bashrc')]

Ten Useful Python One-Linger Programs You Must Know

5. Writing files

Just like reading files, the process of writing files in this beautiful language is very simple.

with open("file.txt",'a',newline='n') as f: f.write("This is a new line in a file")

This statement allows you to avoid having to close the file handle. So when your app is open, it won't conflict with other apps trying to access it.

You can now use the one-line program you learned for reading files to check that the line was added correctly!

[print(line.strip()) for line in open('file.txt')]

Ten Useful Python One-Linger Programs You Must Know

#6. Create a list of number ranges

Similar to the way other scripting languages ​​like LUA work, Python allows you to generate pre-populated lists whenever Operations lead to predictable results. In this code snippet, we create a list of 10 integers ranging from 0 to 9:

lst = [i for i in range(0,10)]

Printing this list will produce a comma separated list of numbers containing the parameters we discussed earlier.

Ten Useful Python One-Linger Programs You Must Know

7.显示所有用户(在Linux/Unix/BSD中)

想知道在您的特定Linux安装中实际上有多少个用户名吗?Python有一个很好的方法,通过打开“/etc/passwd”文件,在一行中就可以做到这一点。在这种情况下,我们要做的就是从每行的第一个冒号(":")开始删除所有内容。

print('n'.join(line.split(":",1)[0] for line in open("/etc/passwd")))

如果您没有仔细查看该文件,您可能会惊讶地发现,系统创建的用户比您登录时使用的用户和根用户多得多。

Ten Useful Python One-Linger Programs You Must Know

用户列表通常有这么长,因为系统会根据您运行的服务创建自己的身份验证形式。

8.生成随机密码

像任何自尊的语言一样,Python允许你随机化事情,但是它不能不更进一步,允许你在一行中生成密码。诚然,这是一个非常漫长的过程..

pwd = 'ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789 %^*(-_=+)'; print(''.join([pwd[random.randint(0,len(pwd)-1)] for i in range(32)]))

这个特定的代码片段将生成一个32个字符的密码,允许使用空格。根据你的喜好调整。如果您出于某种原因不想在密码中使用空格,请删除字符串声明中的空格。不要忘记导入“随机”库,否则你的代码将无法工作!

Ten Useful Python One-Linger Programs You Must Know

9.查找文本中任何内容的实例

如果您正在阅读一个较长的文件,并试图找出其中有多少个特定表达式的实例,这就有点奇怪了:

import re; len(re.findall('d','The dumb lazy cat doesn't know how to hunt birds.'))

在这个特殊的例子中,我们试图找出字母“d”在它后面的字符串中出现了多少次。通过打印输出,控制台让我们知道这封信有3个实例。您可以使用整个单词和在文件中搜索来实现这一点。

Ten Useful Python One-Linger Programs You Must Know

10.将十六进制表达式转换为明文

通过一点迭代魔法,可以用一个简单的表达式将十六进制代码转换成纯文本:

print(''.join(chr(int(''.join(i), 16)) for i in zip(*[iter('576f772c2049276d2077726974696e6720696e2068657861646563696d616c21')]*2)))

里面的一大堆胡言乱语iter()是一个十六进制表达式,这段代码将其转换为“哇,我在用十六进制写!”

Ten Useful Python One-Linger Programs You Must Know

常见问题

Python相对于其他语言有多难?

虽然Python确实有一些特定于某些编码风格的缺陷,但由于它在可变类型方面的灵活性,Python提供了比其他语言更友好的初学者氛围。它是一种解释型语言,所以它不需要您处理手动分配内存并确保在不再使用时释放内存的繁琐工作。

Python稳定吗?

Python的开发人员强烈反对用新版本使旧代码无效的想法,并且在历史上一直非常小心地确保向后兼容更旧的代码。在2005年,Python社区不得不处理一个棘手的问题reduce()和许多其他功能从标准库中移除并且必须从Python 3000中的另一个导入。一般来说,这些事情都是公开的,如果您的代码停止正常运行,控制台会提供有用的信息,让您找出原因并做出相应的调整。

Python最好的开发环境是什么?

如果您想使用Python的集成开发环境,有几个跨操作系统的选项可供您选择:

  • 皮查姆

   –如果你真的想献身于Python,就用这个吧。这个IDE只专注于Python,包含大量的工具和库,可以帮助您流畅地编写代码。

  • Visual Studio代码

   –如果您希望最终扩展并学习其他语言,VSCode(在Linux中有时称为Code–OSS,在Arch Linux中称为“Code”包)提供了强大的功能以及针对各种语言的集成编译器。

  • 精力

   –它允许在任何终端模拟器中非常快速地编辑复杂的文本。它有很高的学习曲线,但应该是每个程序员的武器库。

The above is the detailed content of Ten Useful Python One-Linger Programs You Must Know. For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:51CTO.COM. If there is any infringement, please contact admin@php.cn delete
Python's Hybrid Approach: Compilation and Interpretation CombinedPython's Hybrid Approach: Compilation and Interpretation CombinedMay 08, 2025 am 12:16 AM

Pythonusesahybridapproach,combiningcompilationtobytecodeandinterpretation.1)Codeiscompiledtoplatform-independentbytecode.2)BytecodeisinterpretedbythePythonVirtualMachine,enhancingefficiencyandportability.

Learn the Differences Between Python's 'for' and 'while' LoopsLearn the Differences Between Python's 'for' and 'while' LoopsMay 08, 2025 am 12:11 AM

ThekeydifferencesbetweenPython's"for"and"while"loopsare:1)"For"loopsareidealforiteratingoversequencesorknowniterations,while2)"while"loopsarebetterforcontinuinguntilaconditionismetwithoutpredefinediterations.Un

Python concatenate lists with duplicatesPython concatenate lists with duplicatesMay 08, 2025 am 12:09 AM

In Python, you can connect lists and manage duplicate elements through a variety of methods: 1) Use operators or extend() to retain all duplicate elements; 2) Convert to sets and then return to lists to remove all duplicate elements, but the original order will be lost; 3) Use loops or list comprehensions to combine sets to remove duplicate elements and maintain the original order.

Python List Concatenation Performance: Speed ComparisonPython List Concatenation Performance: Speed ComparisonMay 08, 2025 am 12:09 AM

ThefastestmethodforlistconcatenationinPythondependsonlistsize:1)Forsmalllists,the operatorisefficient.2)Forlargerlists,list.extend()orlistcomprehensionisfaster,withextend()beingmorememory-efficientbymodifyinglistsin-place.

How do you insert elements into a Python list?How do you insert elements into a Python list?May 08, 2025 am 12:07 AM

ToinsertelementsintoaPythonlist,useappend()toaddtotheend,insert()foraspecificposition,andextend()formultipleelements.1)Useappend()foraddingsingleitemstotheend.2)Useinsert()toaddataspecificindex,thoughit'sslowerforlargelists.3)Useextend()toaddmultiple

Are Python lists dynamic arrays or linked lists under the hood?Are Python lists dynamic arrays or linked lists under the hood?May 07, 2025 am 12:16 AM

Pythonlistsareimplementedasdynamicarrays,notlinkedlists.1)Theyarestoredincontiguousmemoryblocks,whichmayrequirereallocationwhenappendingitems,impactingperformance.2)Linkedlistswouldofferefficientinsertions/deletionsbutslowerindexedaccess,leadingPytho

How do you remove elements from a Python list?How do you remove elements from a Python list?May 07, 2025 am 12:15 AM

Pythonoffersfourmainmethodstoremoveelementsfromalist:1)remove(value)removesthefirstoccurrenceofavalue,2)pop(index)removesandreturnsanelementataspecifiedindex,3)delstatementremoveselementsbyindexorslice,and4)clear()removesallitemsfromthelist.Eachmetho

What should you check if you get a 'Permission denied' error when trying to run a script?What should you check if you get a 'Permission denied' error when trying to run a script?May 07, 2025 am 12:12 AM

Toresolvea"Permissiondenied"errorwhenrunningascript,followthesesteps:1)Checkandadjustthescript'spermissionsusingchmod xmyscript.shtomakeitexecutable.2)Ensurethescriptislocatedinadirectorywhereyouhavewritepermissions,suchasyourhomedirectory.

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor