logo


Category: Uncategorized

String-Methoden

Ein Beispiel für die Verwendung einer String-Methode:


s = "Hello World"
s = s.replace("World","Python")
Print(s)

Related Course:
Python Programming Bootcamp: Go from zero to hero

Übersicht
Python umfasst diese nützlichen Methoden zur String-Manipulation:



Methode mit Beschreibung
capitalize(Str)
Renditen erste Buchstabe großgeschrieben Zeichenfolge.
Count(Str)
Zählen Sie die Häufigkeit des Wortes str. Es kann auch auf Wörter angewendet werden: s.count("Hello")
find(Str)
Finden Sie die Position des ersten Vorkommens.
Index(Str)
Finden Sie die Position des ersten Vorkommens, Ausnahme wenn nicht gefunden.
isdecimal()
Gibt True zurück, wenn Zeichenfolge decimal ist.
isdigit()
Gibt True zurück, wenn String nur Ziffern enthält.
IsNumeric()
Gibt True zurück, wenn Zeichenfolge nur numerische enthält.
Lower()
Retouren-Zeichenfolge in Kleinbuchstaben.
len(Str)
Gibt die Länge von str zurück.
gross()
Retouren-Zeichenfolge in Großbuchstaben.
ersetzen Sie (alt, neu)
Das erste Argument ersetzt mit dem zweiten Argument.

Python IDEs

Ein Python-IDE installieren


Ein Integrierte Arbeitsumgebung (IDE) ist eine Softwareanwendung für die Programmierung. Neben einfachen Text-Bearbeitung haben sie alle Arten von Funktionen wie Syntax-highlighting, Code-Vervollständigung, Tabs, ein Klassenbrowser und vieles mehr.


Online Python-Interpreters


Die online Dolmetscher funktioniert möglicherweise nicht für alles aber funktioniert für die meisten Anfänger-Tutorials. Ich empfehle eine desktop-IDE oder das offizielle Python-Interpreter.


Übersicht über IDEs (Sie benötigen nur eins)


IDE Author Plattform Beschreibung Preis Herunterladen
PyCharm Jetbrains Windows, Mac OS X, Linux/UNIX Python IDE. Funktionen, einschließlich: Code-Vervollständigung, Code-Inspektionen, on-the-Fly Fehler hervorheben und Schnellkorrekturen € 89 / 1. Jahr. ($ 97,90) Download PyCharm 
Atom (+ Skript Plugin) GitHub Windows, Mac OS X, Linux/UNIX Python IDE. Sie müssen das Skript Plugin download nach der Installation von Atom. Kostenlos. Download Atom.
Pythonista OMZ:Software Apple iOS (iPhone, iPad) Eigenschaften umfassen: Syntax-highlighting, Code-Vervollständigung, interaktive Eingabeaufforderung, Standard und iOS-Module. 9 €. ($ 9,90) Download Pythonista.
Eclipse mit PyDev Aleks Totic Windows, Mac OS X, Linux/UNIX Eigenschaften umfassen: Syntax-Hervorhebung, Codeumgestaltung, grafische Debuggen und mehr. Free Herunterladen 
Eric Python IDE Detlev Offenbach Windows, Linux/UNIX Eigenschaften umfassen: Syntax-Hervorhebung, Auto-Vervollständigung, Klassenkatalog und mehr. Free Herunterladen 
Wing IDE Wingware Windows, Mac OS X, Linux/UNIX Merkmale: Syntax-Hervorhebung, Auto-Vervollständigung, Umgestaltung, Komponententests und Steuern Version. 45 $245 pro Benutzer / eine Lizenz. Herunterladen 
Komodo IDE Komodo Windows, Mac OS X, Linux/UNIX Merkmale: Syntax-Hervorhebung, Dokumentationsbrowser, Ausführen von Code in Zeile, schnelle Lesezeichen und mehr. € 40 bis € 223. ($99 auf $295). Herunterladen 
Skulpt Skulpt Web Python-interpreter Free Führen Sie Online 
Repl.it Amjad Masad, Haya Odeh, Faris Masad und Max Shawabkeh. Web Python-interpreter Free Führen Sie Online 
Ideone Ideone Web Python-interpreter Free Führen Sie Online 
CodePad Steven Hazel Web Python-interpreter Free Führen Sie Online 

Save a dictionary to a file

Given a dictionary such as:


dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}

We can save it to one of these formats:

  • Comma seperated value file (.csv)
  • Json file (.json)
  • Text file (.txt)
  • Pickle file (.pkl)

You could also write to a SQLite database.

Related Course:

save dictionary as csv file

we can write it to a file with the csv module.


import csv

dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
w = csv.writer(open("output.csv", "w"))
for key, val in dict.items():
w.writerow([key, val])

python-write-dictionary-to-csv The dictionary file (csv) can be opened in Google Docs or Excel

save dictionary to json file

If you want to save a dictionary to a json file



import json

dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}

json = json.dumps(dict)
f = open("dict.json","w")
f.write(json)
f.close()


save dictionary to text file (raw, .txt)

You can save your dictionary to a text file using the code below:


dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
f = open("dict.txt","w")
f.write( str(dict) )
f.close()

save dictionary to a pickle file (.pkl)

The pickle module may be used to save dictionaries (or other objects) to a file. The module can serialize and deserialize Python objects.


import pickle
dict = {'Python' : '.py', 'C++' : '.cpp', 'Java' : '.java'}
f = open("file.pkl","wb")
pickle.dump(dict,f)
f.close()

Log functions in Python (Guide)

Log messages can indicate an event has executed.
You can use logging for these purposes:


  • debugging

  • informational messages

  • show warnings

  • show errors

  • show critical messages


The log method to use depends on the severity of the message. Debug messages can help you with programming your applications but are not severe.

Overview:

To use start logging, load the logging module with “import logging”.


import logging
logging.warning('File could not be opened')

We can use all the types of logging:


import logging
logging.debug('Debug message')
logging.info('Informational message')
logging.warning('Warning message')
logging.error('Error mesage')
logging.critical('Critical message')

Logging levels

You can add debug messages to your program, and on release change the logging level to information to hide them. It’s also recommended to save logging messages to a file:


logging.basicConfig(filename='program.log',level=logging.INFO)

To return to debugging mode, change to:


logging.basicConfig(filename='program.log',level=logging.DEBUG)

The standard level is warning.

Practical example

An example of using the log module below:


import logging

x = int(raw_input("Enter a number: "))

if x < 0:
logging.error('Error: x must be positive.')
exit(0)
else:
print("Starting calculation")
logging.info("Calculation started.")

 

How to write Comments in Python (Guide)

Comments can be added to Python programs, this makes your code easy to understand by others. A comment is human readable text that is not executed by Python.

It increases the readability of your code, comments are written for software developers. Comments are ignored by the Python interpreter

Python has several possibilities to add comments.

Related Course:
Python Programming Bootcamp: Go from zero to hero

Python commenting

A single line comment can be added by using the hash (#) character. The hash (#) is added for every line that should be commented.

You can put any comment in the code:

# Show the world a message
print('Hello World')

If you use a modern Python IDE, it will highlight your comment in another color. Each comment is ignored by Python.

If a statement is put before the comment, the statement is run but the comment is ignored.

print("Run this")  # Ignore this

The code above will only show “Run this” in the terminal.

Python Mutliline Comments

Python does not have a way to add multiline comments with special characters.
A language like Java or C++ allows you to write multiline comments like this:

/* You can write
multiline comments
like this in C++ */

Then the whole block is ignored, but Python doesn’t have native multiline commenting support.

In Python you can create multiline comments like this:

# You can write
# multiline comments
# like this in Python

Another way to do this is using triple quotes ‘’’ characters, this is ignored by Python but officially that’s for documentation not comments.

'''
We can type multiple lines of commment
if we use the indicator.
'''

Why comments?

There are two main reasons to add comments to your code.

1) to make your own code more readable
2) to make your code understandable for others

Sometimes developers add notes or todo lists in their code.

As a developer you write a lot of code, and you may forget what a piece of code does. Commenting helps you increase your productivity.

Related Course: Python Programming Bootcamp: Go from zero to hero

Array find in Python

Arrays are usually referred to as lists. For convience, lets call them arrays in this article.

Python has a method to search for an element in an array, known as index().
We can find an index using:


x = ['p','y','t','h','o','n']
print(x.index('o'))

Arrays start with the index zero (0) in Python:

python-string Python character array

If you would run x.index(‘p’) you would get zero as output (first index).

Related course:

Array duplicates: If the array contains duplicates, the index() method will only return the first element.

Find multiple occurences

If you want multiple to find multiple occurrences of an element, use the lambda function below.


get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]

Find in string arrays

To find an element in a string array use:


x = ["Moon","Earth","Jupiter"]
print(x.index("Earth"))

You could use this code if you want to find multiple occurrences:



x = ["Moon","Earth","Jupiter","Neptune","Earth","Venus"]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes("Earth",x))


Find in numeric array

The index method works on numeric arrays too:


x = [5,1,7,0,3,4]
print(x.index(7))

To find multiple occurrences you can use this lambda function:



x = [5,1,7,0,3,4,5,3,2,6,7,3,6]
get_indexes = lambda x, xs: [i for (y, i) in zip(xs, range(len(xs))) if x == y]
print(get_indexes(7,x))



123