Karakterlánc-módszer
Két lehetőség kínálkozik arra, hogy a Pythonban egy sztringen belül találjon egy részstruktúrát, find()
és rfind()
.
Mindegyik visszaadja azt a pozíciót, amelyen az alstring található. A kettő közötti különbség az, hogy find()
a legalacsonyabb és rfind()
a legmagasabb pozíciót adja vissza.
Opcionális kezdő és befejező argumentummal lehet megadni, hogy az alszöveg keresését a karakterlánc egyes részein belül korlátozzuk.
Példa:
>>> string = "Don't you call me a mindless philosopher, you overweight glob of grease!" >>> string.find('you') 6 >>> string.rfind('you') 42
Ha az alszöveg nem található, akkor -1 adódik vissza.
>>> 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
Több információ:
Húr metódusok dokumentációja.
Karakterlánc-csatlakozási módszer
A str.join(iterable)
módszert az összes elem összekapcsolására használjuk iterable
egy megadott karakterlánccal str
. Ha az iterable nem string értékeket tartalmaz, akkor az TypeError kivételt vet fel.
iterable
: A karakterlánc összes iterációja. Lehetne egy listát a húrokról, a karakterláncokról vagy akár egy sima karakterláncról is.
Példák
Csatlakozzon a húrok ist ":"
print ":".join(["freeCodeCamp", "is", "fun"])
Kimenet
freeCodeCamp:is:fun
Csatlakozzon egy sor húrhoz " and "
print " and ".join(["A", "B", "C"])
Kimenet
A and B and C
Helyezzen be egy " "
karaktert a karakterlánc minden karaktere után
print " ".join("freeCodeCamp")
Kimenet:
f r e e C o d e C a m p
Csatlakozás üres húrral.
list1 = ['p','r','o','g','r','a','m'] print("".join(list1))
Kimenet:
program
Csatlakozás halmazokkal.
test = {'2', '1', '3'} s = ', ' print(s.join(test))
Kimenet:
2, 3, 1
Több információ:
Python dokumentáció a String Join-ról
Karakterlánc-csere módszer
A str.replace(old, new, max)
metódust arra használjuk, hogy az alszöveget old
a karakterlánccal new
összesen max
többször cseréljük le . Ez a módszer a string új példányát adja vissza a cserével. Az eredeti karakterlánc str
változatlan.
Példák
- Cserélje le az összes előfordulását a következőre
"is"
:"WAS"
string = "This is nice. This is good." newString = string.replace("is","WAS") print(newString)
Kimenet
ThWAS WAS nice. ThWAS WAS good.
- Cserélje ki az első 2 előfordulásával
"is"
együtt"WAS"
string = "This is nice. This is good." newString = string.replace("is","WAS", 2) print(newString)
Kimenet
ThWAS WAS nice. This is good.
Több információ:
További információ a karakterlánc-cseréről a Python-dokumentumokban
String Strip módszer
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