String-Suchmethode
Es gibt zwei Möglichkeiten, einen Teilstring innerhalb eines Strings in Python zu finden, find()
und rfind()
.
Jeder gibt die Position zurück, an der sich der Teilstring befindet. Der Unterschied zwischen den beiden besteht darin, dass find()
die niedrigste Position und rfind()
die höchste Position zurückgegeben werden.
Optionale Start- und Endargumente können bereitgestellt werden, um die Suche nach dem Teilstring auf Teile der Zeichenfolge zu beschränken.
Beispiel:
>>> string = "Don't you call me a mindless philosopher, you overweight glob of grease!" >>> string.find('you') 6 >>> string.rfind('you') 42
Wenn der Teilstring nicht gefunden wird, wird -1 zurückgegeben.
>>> string = "Don't you call me a mindless philosopher, you overweight glob of grease!" >>> string.find('you', 43) # find 'you' in string anywhere from position 43 to the end of the string -1
Mehr Informationen:
Dokumentation zu String-Methoden.
String Join-Methode
Die str.join(iterable)
Methode wird verwendet, um alle Elemente in einem iterable
mit einer angegebenen Zeichenfolge zu verbinden str
. Wenn die Iterable Werte enthält, die keine Zeichenfolgen sind, wird eine TypeError-Ausnahme ausgelöst.
iterable
: Alle iterablen Zeichenfolgen. Könnte eine Liste von Zeichenfolgen, ein Tupel von Zeichenfolgen oder sogar eine einfache Zeichenfolge sein.
Beispiele
Verbinden Sie eine Reihe von Zeichenfolgen mit ":"
print ":".join(["freeCodeCamp", "is", "fun"])
Ausgabe
freeCodeCamp:is:fun
Verbinden Sie ein Tupel von Zeichenfolgen mit " and "
print " and ".join(["A", "B", "C"])
Ausgabe
A and B and C
Fügen Sie " "
nach jedem Zeichen ein Zeichen in eine Zeichenfolge ein
print " ".join("freeCodeCamp")
Ausgabe:
f r e e C o d e C a m p
Mit leerer Zeichenfolge verbinden.
list1 = ['p','r','o','g','r','a','m'] print("".join(list1))
Ausgabe:
program
Mit Sets verbinden.
test = {'2', '1', '3'} s = ', ' print(s.join(test))
Ausgabe:
2, 3, 1
Mehr Informationen:
Python-Dokumentation zu String Join
String Replace-Methode
Das str.replace(old, new, max)
Verfahren wird verwendet , um die Teilkette zu ersetzen old
mit dem String new
für insgesamt max
mal. Diese Methode gibt eine neue Kopie der Zeichenfolge mit dem Ersatz zurück. Die ursprüngliche Zeichenfolge str
bleibt unverändert.
Beispiele
- Ersetzen Sie alle Vorkommen von
"is"
durch"WAS"
string = "This is nice. This is good." newString = string.replace("is","WAS") print(newString)
Ausgabe
ThWAS WAS nice. ThWAS WAS good.
- Ersetzen Sie die ersten 2 Vorkommen von
"is"
durch"WAS"
string = "This is nice. This is good." newString = string.replace("is","WAS", 2) print(newString)
Ausgabe
ThWAS WAS nice. This is good.
Mehr Informationen:
Weitere Informationen zum Ersetzen von Zeichenfolgen finden Sie in den Python-Dokumenten
String Strip-Methode
There are three options for stripping characters from a string in Python, lstrip()
, rstrip()
and strip()
.
Each will return a copy of the string with characters removed, at from the beginning, the end or both beginning and end. If no arguments are given the default is to strip whitespace characters.
Example:
>>> string = ' Hello, World! ' >>> strip_beginning = string.lstrip() >>> strip_beginning 'Hello, World! ' >>> strip_end = string.rstrip() >>> strip_end ' Hello, World!' >>> strip_both = string.strip() >>> strip_both 'Hello, World!'
An optional argument can be provided as a string containing all characters you wish to strip.
>>> url = 'www.example.com/' >>> url.strip('w./') 'example.com'
However, do notice that only the first .
got stripped from the string. This is because the strip
function only strips the argument characters that lie at the left or rightmost. Since w comes before the first .
they get stripped together, whereas ‘com’ is present in the right end before the .
after stripping /
.
String Split Method
The split()
function is commonly used for string splitting in Python.
The split()
method
Template: string.split(separator, maxsplit)
separator
: The delimiter string. You split the string based on this character. For eg. it could be ” ”, ”:”, ”;” etc
maxsplit
: The number of times to split the string based on the separator
. If not specified or -1, the string is split based on all occurrences of the separator
This method returns a list of substrings delimited by the separator
Examples
Split string on space: ” ”
string = "freeCodeCamp is fun." print(string.split(" "))
Output:
['freeCodeCamp', 'is', 'fun.']
Split string on comma: ”,”
string = "freeCodeCamp,is fun, and informative" print(string.split(","))
Output:
['freeCodeCamp', 'is fun', ' and informative']
No separator
specified
string = "freeCodeCamp is fun and informative" print(string.split())
Output:
['freeCodeCamp', 'is', 'fun', 'and', 'informative']
Note: If no separator
is specified, then the string is stripped of all whitespace
string = "freeCodeCamp is fun and informative" print(string.split())
Output:
['freeCodeCamp', 'is', 'fun', 'and', 'informative']
Split string using maxsplit
. Here we split the string on ” ” twice:
string = "freeCodeCamp is fun and informative" print(string.split(" ", 2))
Output:
['freeCodeCamp', 'is', 'fun and informative']
More Information
Check out the Python docs on string splitting