שיטת מיתרי מחרוזת
ישנן שתי אפשרויות למציאת מצע בתוך מחרוזת בפייתון find()
ו- rfind()
.
כל אחד מהם יחזיר את המיקום בו נמצא המצע. ההבדל בין השניים הוא find()
שמחזיר את המיקום הנמוך ביותר, rfind()
ומחזיר את המיקום הגבוה ביותר.
ניתן לספק טיעוני התחלה וסיום אופציונליים כדי להגביל את החיפוש אחר המזרק בחלקים של המחרוזת.
דוגמא:
>>> string = "Don't you call me a mindless philosopher, you overweight glob of grease!" >>> string.find('you') 6 >>> string.rfind('you') 42
אם המצע לא נמצא, -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
עוד מידע:
תיעוד שיטות מחרוזת.
שיטת הצטרפות למיתרים
str.join(iterable)
השיטה משמשת להצטרף כל האלמנטים בתוך iterable
עם מחרוזת שצוינה str
. אם ה- iterable מכיל ערכים שאינם מחרוזת, הוא מעלה חריג מסוג TypeRror.
iterable
: כל חזרות המיתר. יכול להיות שרשימה של מיתרים, חוט של מחרוזת או אפילו מחרוזת רגילה.
דוגמאות
הצטרף עם מיתרים ":"
print ":".join(["freeCodeCamp", "is", "fun"])
תְפוּקָה
freeCodeCamp:is:fun
הצטרף לכדי מיתרי מיתרים עם " and "
print " and ".join(["A", "B", "C"])
תְפוּקָה
A and B and C
הכנס " "
מחרוזת אחרי כל תו
print " ".join("freeCodeCamp")
תְפוּקָה:
f r e e C o d e C a m p
מצטרף עם מחרוזת ריקה.
list1 = ['p','r','o','g','r','a','m'] print("".join(list1))
תְפוּקָה:
program
מצטרף לסטים.
test = {'2', '1', '3'} s = ', ' print(s.join(test))
תְפוּקָה:
2, 3, 1
עוד מידע:
תיעוד פייתון על מחרוזת הצטרפות
שיטת החלפת מחרוזות
str.replace(old, new, max)
השיטה משמשת כדי להחליף את המחרוזת old
עם המחרוזת new
עבור סכום כולל של max
פעמים. שיטה זו מחזירה עותק חדש של המחרוזת עם ההחלפה. המחרוזת המקורית str
אינה משתנה.
דוגמאות
- החלף את כל המופעים
"is"
עם"WAS"
string = "This is nice. This is good." newString = string.replace("is","WAS") print(newString)
תְפוּקָה
ThWAS WAS nice. ThWAS WAS good.
- החלף את 2 ההופעות הראשונות של
"is"
ב-"WAS"
string = "This is nice. This is good." newString = string.replace("is","WAS", 2) print(newString)
תְפוּקָה
ThWAS WAS nice. This is good.
עוד מידע:
קרא עוד על החלפת מחרוזות במסמכי Python
שיטת רצועת מיתרים
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