Χορδές Python (με παραδείγματα)

Σε αυτό το σεμινάριο θα μάθετε να δημιουργείτε, να μορφοποιείτε, να τροποποιείτε και να διαγράφετε συμβολοσειρές στο Python. Επίσης, θα εισαχθείτε σε διάφορες λειτουργίες και λειτουργίες συμβολοσειρών.

Βίντεο: Python Strings

Τι είναι το String in Python;

Μια συμβολοσειρά είναι μια ακολουθία χαρακτήρων.

Ένας χαρακτήρας είναι απλά ένα σύμβολο. Για παράδειγμα, η αγγλική γλώσσα έχει 26 χαρακτήρες.

Οι υπολογιστές δεν ασχολούνται με χαρακτήρες, ασχολούνται με αριθμούς (δυαδικά). Ακόμα κι αν μπορεί να δείτε χαρακτήρες στην οθόνη σας, αποθηκεύεται και χειρίζεται εσωτερικά ως συνδυασμός 0s και 1s.

Αυτή η μετατροπή χαρακτήρα σε αριθμό ονομάζεται κωδικοποίηση και η αντίστροφη διαδικασία αποκωδικοποιεί. Τα ASCII και Unicode είναι μερικές από τις δημοφιλείς κωδικοποιήσεις που χρησιμοποιούνται.

Στο Python, μια συμβολοσειρά είναι μια ακολουθία χαρακτήρων Unicode. Το Unicode εισήχθη για να συμπεριλάβει κάθε χαρακτήρα σε όλες τις γλώσσες και να φέρει ομοιομορφία στην κωδικοποίηση. Μπορείτε να μάθετε για το Unicode από το Python Unicode.

Πώς να δημιουργήσετε μια συμβολοσειρά στο Python;

Οι χορδές μπορούν να δημιουργηθούν περικλείοντας χαρακτήρες μέσα σε ένα μόνο απόσπασμα ή διπλά εισαγωγικά. Ακόμα και τριπλά εισαγωγικά μπορούν να χρησιμοποιηθούν στο Python, αλλά γενικά χρησιμοποιούνται για την απεικόνιση πολλών γραμμών και κορδονιών.

 # defining strings in Python # all of the following are equivalent my_string = 'Hello' print(my_string) my_string = "Hello" print(my_string) my_string = '''Hello''' print(my_string) # triple quotes string can extend multiple lines my_string = """Hello, welcome to the world of Python""" print(my_string)

Όταν εκτελείτε το πρόγραμμα, η έξοδος θα είναι:

 Γεια σας Γεια σας Γεια σας, καλώς ήλθατε στον κόσμο της Python

Πώς να αποκτήσετε πρόσβαση σε χαρακτήρες σε μια συμβολοσειρά;

Μπορούμε να αποκτήσουμε πρόσβαση σε μεμονωμένους χαρακτήρες χρησιμοποιώντας ευρετηρίαση και μια σειρά χαρακτήρων χρησιμοποιώντας τεμαχισμό. Το ευρετήριο ξεκινά από το 0. Η προσπάθεια πρόσβασης σε έναν χαρακτήρα εκτός εύρους ευρετηρίου θα αυξήσει ένα IndexError. Ο δείκτης πρέπει να είναι ακέραιος. Δεν μπορούμε να χρησιμοποιήσουμε πλωτήρες ή άλλους τύπους, αυτό θα οδηγήσει σε TypeError.

Η Python επιτρέπει αρνητική ευρετηρίαση για τις ακολουθίες της.

Ο δείκτης -1αναφέρεται στο τελευταίο στοιχείο, -2στο δεύτερο τελευταίο στοιχείο και ούτω καθεξής. Μπορούμε να αποκτήσουμε πρόσβαση σε μια σειρά στοιχείων σε μια συμβολοσειρά χρησιμοποιώντας τον τελεστή τεμαχισμού :(άνω και κάτω τελεία).

 #Accessing string characters in Python str = 'programiz' print('str = ', str) #first character print('str(0) = ', str(0)) #last character print('str(-1) = ', str(-1)) #slicing 2nd to 5th character print('str(1:5) = ', str(1:5)) #slicing 6th to 2nd last character print('str(5:-2) = ', str(5:-2))

Όταν εκτελούμε το παραπάνω πρόγραμμα, λαμβάνουμε την ακόλουθη έξοδο:

 str = programiz str (0) = p str (-1) = z str (1: 5) = rogr str (5: -2) = am

Εάν προσπαθήσουμε να αποκτήσουμε πρόσβαση σε ένα ευρετήριο εκτός εύρους ή να χρησιμοποιήσουμε αριθμούς διαφορετικούς από έναν ακέραιο, θα λάβουμε σφάλματα.

 # index must be in range >>> my_string(15)… IndexError: string index out of range # index must be an integer >>> my_string(1.5)… TypeError: string indices must be integers

Ο τεμαχισμός μπορεί να απεικονιστεί καλύτερα λαμβάνοντας υπόψη ότι ο δείκτης βρίσκεται μεταξύ των στοιχείων όπως φαίνεται παρακάτω.

Εάν θέλουμε να αποκτήσουμε πρόσβαση σε ένα εύρος, χρειαζόμαστε το ευρετήριο που θα κόψει το τμήμα από τη συμβολοσειρά.

String Slicing στο Python

Πώς να αλλάξετε ή να διαγράψετε μια συμβολοσειρά;

Οι χορδές είναι αμετάβλητες. Αυτό σημαίνει ότι τα στοιχεία μιας συμβολοσειράς δεν μπορούν να αλλάξουν όταν έχουν αντιστοιχιστεί. Μπορούμε απλώς να αλλάξουμε διαφορετικές συμβολοσειρές στο ίδιο όνομα.

 >>> my_string = 'programiz' >>> my_string(5) = 'a'… TypeError: 'str' object does not support item assignment >>> my_string = 'Python' >>> my_string 'Python'

Δεν μπορούμε να διαγράψουμε ή να αφαιρέσουμε χαρακτήρες από μια συμβολοσειρά. Ωστόσο, η πλήρης διαγραφή της συμβολοσειράς είναι δυνατή χρησιμοποιώντας τη delλέξη-κλειδί.

 >>> del my_string(1)… TypeError: 'str' object doesn't support item deletion >>> del my_string >>> my_string… NameError: name 'my_string' is not defined

Λειτουργίες Python String

Υπάρχουν πολλές λειτουργίες που μπορούν να εκτελεστούν με συμβολοσειρές που το καθιστούν έναν από τους πιο χρησιμοποιούμενους τύπους δεδομένων στην Python.

Για να μάθετε περισσότερα σχετικά με τους διαθέσιμους τύπους δεδομένων στο Python, επισκεφθείτε: Τύποι δεδομένων Python

Συνδυασμός δύο ή περισσότερων χορδών

Η ένωση δύο ή περισσοτέρων χορδών σε μία ονομάζεται συνένωση.

Ο χειριστής + το κάνει αυτό στο Python. Απλά γράφοντας δύο γραμματοσειρές συμβόλων μαζί τους συνδυάζει επίσης.

Ο χειριστής * μπορεί να χρησιμοποιηθεί για να επαναλάβει τη συμβολοσειρά για συγκεκριμένες φορές.

 # Python String Operations str1 = 'Hello' str2 ='World!' # using + print('str1 + str2 = ', str1 + str2) # using * print('str1 * 3 =', str1 * 3)

Όταν εκτελούμε το παραπάνω πρόγραμμα, λαμβάνουμε την ακόλουθη έξοδο:

str1 + str2 = Γεια σου Κόσμος! str1 * 3 = Γεια σας Γεια σας

Η συγγραφή δύο γραμματοσειρών συμβολοσειρών μαζί τους συνδυάζει επίσης όπως + χειριστή.

Αν θέλουμε να συνδυάσουμε χορδές σε διαφορετικές γραμμές, μπορούμε να χρησιμοποιήσουμε παρενθέσεις.

 >>> # two string literals together >>> 'Hello ''World!' 'Hello World!' >>> # using parentheses >>> s = ('Hello '… 'World') >>> s 'Hello World'

Επανάληψη μέσω συμβολοσειράς

Μπορούμε να επαναλάβουμε μια συμβολοσειρά χρησιμοποιώντας ένα για βρόχο. Εδώ είναι ένα παράδειγμα για να μετρήσετε τον αριθμό των l σε μια συμβολοσειρά.

 # Iterating through a string count = 0 for letter in 'Hello World': if(letter == 'l'): count += 1 print(count,'letters found')

Όταν εκτελούμε το παραπάνω πρόγραμμα, λαμβάνουμε την ακόλουθη έξοδο:

 Βρέθηκαν 3 γράμματα

Δοκιμή μέλους συμβολοσειράς

We can test if a substring exists within a string or not, using the keyword in.

 >>> 'a' in 'program' True >>> 'at' not in 'battle' False

Built-in functions to Work with Python

Various built-in functions that work with sequence work with strings as well.

Some of the commonly used ones are enumerate() and len(). The enumerate() function returns an enumerate object. It contains the index and value of all the items in the string as pairs. This can be useful for iteration.

Similarly, len() returns the length (number of characters) of the string.

 str = 'cold' # enumerate() list_enumerate = list(enumerate(str)) print('list(enumerate(str) = ', list_enumerate) #character count print('len(str) = ', len(str))

When we run the above program, we get the following output:

 list(enumerate(str) = ((0, 'c'), (1, 'o'), (2, 'l'), (3, 'd')) len(str) = 4

Python String Formatting

Escape Sequence

If we want to print a text like He said, "What's there?", we can neither use single quotes nor double quotes. This will result in a SyntaxError as the text itself contains both single and double quotes.

 >>> print("He said, "What's there?"")… SyntaxError: invalid syntax >>> print('He said, "What's there?"')… SyntaxError: invalid syntax

One way to get around this problem is to use triple quotes. Alternatively, we can use escape sequences.

An escape sequence starts with a backslash and is interpreted differently. If we use a single quote to represent a string, all the single quotes inside the string must be escaped. Similar is the case with double quotes. Here is how it can be done to represent the above text.

 # using triple quotes print('''He said, "What's there?"''') # escaping single quotes print('He said, "What\'s there?"') # escaping double quotes print("He said, "What's there? "")

When we run the above program, we get the following output:

 He said, "What's there?" He said, "What's there?" He said, "What's there?"

Here is a list of all the escape sequences supported by Python.

Escape Sequence Description
ewline Backslash and newline ignored
\ Backslash
\' Single quote
" Double quote
a ASCII Bell
 ASCII Backspace
f ASCII Formfeed
ASCII Linefeed
ASCII Carriage Return
ASCII Horizontal Tab
v ASCII Vertical Tab
ooo Character with octal value ooo
xHH Character with hexadecimal value HH

Here are some examples

 >>> print("C:\Python32\Lib") C:Python32Lib >>> print("This is printedin two lines") This is printed in two lines >>> print("This is x48x45x58 representation") This is HEX representation

Raw String to ignore escape sequence

Sometimes we may wish to ignore the escape sequences inside a string. To do this we can place r or R in front of the string. This will imply that it is a raw string and any escape sequence inside it will be ignored.

 >>> print("This is x61 good example") This is a good example >>> print(r"This is x61 good example") This is x61 good example

The format() Method for Formatting Strings

The format() method that is available with the string object is very versatile and powerful in formatting strings. Format strings contain curly braces () as placeholders or replacement fields which get replaced.

We can use positional arguments or keyword arguments to specify the order.

 # Python string format() method # default(implicit) order default_order = "(), () and ()".format('John','Bill','Sean') print('--- Default Order ---') print(default_order) # order using positional argument positional_order = "(1), (0) and (2)".format('John','Bill','Sean') print('--- Positional Order ---') print(positional_order) # order using keyword argument keyword_order = "(s), (b) and (j)".format(j='John',b='Bill',s='Sean') print('--- Keyword Order ---') print(keyword_order)

When we run the above program, we get the following output:

 --- Default Order --- John, Bill and Sean --- Positional Order --- Bill, John and Sean --- Keyword Order --- Sean, Bill and John

The format() method can have optional format specifications. They are separated from the field name using colon. For example, we can left-justify <, right-justify > or center ^ a string in the given space.

Μπορούμε επίσης να μορφοποιήσουμε ακέραιους αριθμούς ως δυαδικό, δεκαεξαδικό, κ.λπ. και τα επιπλέοντα μπορούν να στρογγυλοποιηθούν ή να εμφανιστούν σε εκθετική μορφή. Υπάρχουν τόνοι μορφοποίησης που μπορείτε να χρησιμοποιήσετε. Επισκεφθείτε εδώ για όλες τις διαθέσιμες μορφές συμβολοσειρών με τη format()μέθοδο.

 >>> # formatting integers >>> "Binary representation of (0) is (0:b)".format(12) 'Binary representation of 12 is 1100' >>> # formatting floats >>> "Exponent representation: (0:e)".format(1566.345) 'Exponent representation: 1.566345e+03' >>> # round off >>> "One third is: (0:.3f)".format(1/3) 'One third is: 0.333' >>> # string alignment >>> "|(:10)|".format('butter','bread','ham') '|butter | bread | ham|'

Παλιό στυλ μορφοποίησης

Μπορούμε ακόμη και να διαμορφώσουμε χορδές όπως το παλιό sprintf()στυλ που χρησιμοποιείται στη γλώσσα προγραμματισμού Γ. Χρησιμοποιούμε τον %χειριστή για να το επιτύχουμε.

 >>> x = 12.3456789 >>> print('The value of x is %3.2f' %x) The value of x is 12.35 >>> print('The value of x is %3.4f' %x) The value of x is 12.3457

Κοινές μέθοδοι συμβολοσειράς Python

Υπάρχουν πολλές διαθέσιμες μέθοδοι με το αντικείμενο συμβολοσειράς. Η format()μέθοδος που αναφέραμε παραπάνω είναι μία από αυτές. Μερικές από τις μεθόδους που χρησιμοποιούνται συνήθως είναι lower(), upper(), join(), split(), find(), replace()κ.λπ. Εδώ είναι μια πλήρης λίστα με όλα τα ενσωματωμένα μεθόδους για την εργασία με χορδές σε Python.

 >>> "PrOgRaMiZ".lower() 'programiz' >>> "PrOgRaMiZ".upper() 'PROGRAMIZ' >>> "This will split all words into a list".split() ('This', 'will', 'split', 'all', 'words', 'into', 'a', 'list') >>> ' '.join(('This', 'will', 'join', 'all', 'words', 'into', 'a', 'string')) 'This will join all words into a string' >>> 'Happy New Year'.find('ew') 7 >>> 'Happy New Year'.replace('Happy','Brilliant') 'Brilliant New Year'

ενδιαφέροντα άρθρα...