Python-strengmetoder forklaret med eksempler
String Find Method
Der er to muligheder for at finde en substring i en streng i Python, find()
og rfind()
.
Hver vil returnere den position, som substratet er fundet på. Forskellen mellem de to er, at find()
returnerer den laveste position og rfind()
returnerer den højeste position.
Valgfri start- og slutargument kan leveres for at begrænse søgningen efter understrengen til inden for dele af strengen.
Eksempel:
>>> string = "Don't you call me a mindless philosopher, you overweight glob of grease!" >>> string.find('you') 6 >>> string.rfind('you') 42
Hvis understrengen ikke findes, returneres -1.
>>> 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
Mere information:
Strengmetodokumentation.
Metode til strengtilslutning
Den str.join(iterable)
metode bruges til at slutte sig til alle elementer i en iterable
med en angivne streng str
. Hvis iterablen indeholder værdier, der ikke er streng, hæver den en TypeError-undtagelse.
iterable
: Alle iterables af streng. Kunne en liste over strenge, tuple af streng eller endda en almindelig streng.
Eksempler
Deltag i en streng ":"
print ":".join(["freeCodeCamp", "is", "fun"])
Produktion
freeCodeCamp:is:fun
Deltag i en streng streng med " and "
print " and ".join(["A", "B", "C"])
Produktion
A and B and C
Indsæt en " "
efter hvert tegn i en streng
print " ".join("freeCodeCamp")
Produktion:
f r e e C o d e C a m p
Deltager med tom streng.
list1 = ['p','r','o','g','r','a','m'] print("".join(list1))
Produktion:
program
Deltager med sæt.
test = {'2', '1', '3'} s = ', ' print(s.join(test))
Produktion:
2, 3, 1
Mere information:
Python-dokumentation om strengtilslutning
Metode til udskiftning af streng
Den str.replace(old, new, max)
metode, der anvendes til at erstatte delstreng old
med strengen new
i alt max
gange. Denne metode returnerer en ny kopi af strengen med erstatningen. Den originale streng str
er uændret.
Eksempler
- Erstat alle forekomster af
"is"
med"WAS"
string = "This is nice. This is good." newString = string.replace("is","WAS") print(newString)
Produktion
ThWAS WAS nice. ThWAS WAS good.
- Erstat de første 2 forekomster af
"is"
med"WAS"
string = "This is nice. This is good." newString = string.replace("is","WAS", 2) print(newString)
Produktion
ThWAS WAS nice. This is good.
Mere information:
Læs mere om udskiftning af strenge i Python-dokumenterne
String Strip Method
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
Den split()
funktion er almindeligt anvendt til snor opdeling i Python.
den split()
metode
Skabelon: string.split(separator, maxsplit)
separator
: Afgrænsningsstrengen. Du deler strengen ud fra dette tegn. For f.eks. det kunne være " ", ":", ";" etc
maxsplit
: Antallet af gange, som strengen skal deles ud fra separator
. Hvis ikke angivet eller -1, deles strengen ud fra alle forekomster afseparator
Denne metode returnerer en liste over understrenge afgrænset af separator
Eksempler
Opdel streng på plads: ””
string = "freeCodeCamp is fun." print(string.split(" "))
Produktion:
['freeCodeCamp', 'is', 'fun.']
Opdel streng på komma: ”,”
string = "freeCodeCamp,is fun, and informative" print(string.split(","))
Produktion:
['freeCodeCamp', 'is fun', ' and informative']
Ingen separator
specificeret
string = "freeCodeCamp is fun and informative" print(string.split())
Produktion:
['freeCodeCamp', 'is', 'fun', 'and', 'informative']
Bemærk: Hvis der ikke separator
er angivet nej , fjernes strengen fra al hvid plads
string = "freeCodeCamp is fun and informative" print(string.split())
Produktion:
['freeCodeCamp', 'is', 'fun', 'and', 'informative']
Opdel streng ved hjælp af maxsplit
. Her deler vi strengen på ”” to gange:
string = "freeCodeCamp is fun and informative" print(string.split(" ", 2))
Produktion:
['freeCodeCamp', 'is', 'fun and informative']
Mere information
Tjek Python-dokumenterne om strengopdeling