Write a Program That Reads in Three Strings and Sorts Them Lexicographically. Python

So nosotros've seen numbers, but what well-nigh text? This page is well-nigh the Python cord, which is the go-to Python data type for storing and using text in Python. And so, in Python, a piece of text is called a string and you lot can perform all kinds of operations on a string. Just let'due south starting time with the basics first!

What is a Python string?

The following is a formal definition of what a cord is:

String
A string in Python is a sequence of characters

In even simpler terms, a string is a piece of text. Strings are not only a Python matter. Information technology'south a well-known term in the field of informatics and means the same thing in most other languages as well. Now that nosotros know what a string is, we'll look at how to create a cord.

Buy Me A Coffee Give thanks yous for reading my tutorials. I utilise ads to go along writing free articles, I hope you lot empathise! Support me past disabling your adblocker on my website or, alternatively, buy me a java.

How to create a Python string

A Python string needs quotes around it for information technology to be recognized equally such, like this:

>>> 'Hello, World' 'Hello, Globe'

Because of the quotes, Python understands this is a sequence of characters and non a command, number, or variable.

And just similar with numbers, some of the operators nosotros learned before work on Python strings too. Try information technology with the following expressions:

>>> 'a' + 'b' 'ab' >>> 'ab' * 4 'abababab' >>> 'a' - 'b' Traceback (most contempo call last):   File "<stdin>", line 1, in <module> TypeError: unsupported operand blazon(s) for -: 'str' and 'str'

This is what happens in the code above:

  • The plus operator glues ii Python strings together.
  • The multiplication operator repeats our Python string the given number of times.
  • The minus operator doesn't work on a Python cord and produces an error. If you want to remove parts of a string, there are other methods that you'll learn most later on.

Unmarried or double quotes?

We've used single quotes, but Python accepts double-quotes effectually a string as well:

>>> "a" + "b" 'ab'

Note that these are non two unmarried quotes next to each other. It's the character that's often found next to the enter key on your keyboard. Yous need to press shift together with this key to get a double quote.

As y'all can see from its respond, Python itself seems to prefer single quotes. It looks more clear, and Python tries to exist as articulate and well readable equally it can. So why does it support both? Information technology's because it allows you to use strings that incorporate a quote.

In the first example beneath, we use double quotes. Hence at that place's no problem with the single quote in the word it's. However, in the second example, we try to use single quotes. Python sees the quote in the word information technology's and thinks this is the end of the string! The post-obit letter, "s", causes a syntax fault. A syntax error is a character or string incorrectly placed in a command or instruction that causes a failure in execution.

In other words, Python doesn't understand the s at that spot, because it expects the string to be concluded already, and fails with an error:

>>> mystring = "Information technology's a string, with a unmarried quote!" >>> mystring = 'Information technology's a string, with a single quote!'   File "<stdin>", line 1     mystring = 'It'south a string, with a single quote!'                    ^ SyntaxError: invalid syntax

As you can see, fifty-fifty the syntax highlighter on the code block above gets dislocated! And as you tin also see, Python points out the verbal location of where it encountered the error. Python errors tend to be very helpful, so look closely at them and you'll often be able to pinpoint what'southward going wrong.

Escaping

At that place's really another way around this problem, called escaping. You lot can escape a special character, like a quote, with a backward slash:

>>> mystring = 'It\'southward an escaped quote!' >>> mystring "Information technology's an escaped quote!"

You tin can too escape double quotes within a double-quoted string:

>>> mystring = "I'1000 a so-called \"script kiddie\"" >>> mystring 'I\'m a so-called "script kiddie"'

Here, again, you lot see Python's preference for single quotes strings. Even though nosotros used double quotes, Python echos the string back to us using single quotes. It's yet the same string though, it'due south just represented differently. One time you lot start press strings to the screen, you'll see the evidence of this.

So which 1 should you utilize? It'due south simple: ever opt for the selection in which you need the to the lowest degree amount of escapes because these escapes make your Python strings less readable.

Multiline strings

Python also has syntax for creating multiline strings, using triple quotes. By this I mean iii double quotes or three single quotes, both work merely I'll demonstrate with double quotes:

>>> my_big_string = """This is line 1, ... this is line 2, ... this is line 3."""

The overnice thing here is that you can apply both single and double quotes within a multiline string. So y'all can use triple quotes to cleanly create strings that contain both single and double quotes:

>>> line = """He said: "Hello, I've got a question" from the audience"""

String operations

Strings come up with a number of handy, built-in operations you tin can execute. I'll show you just a couple here since I don't want to divert your attending from the tutorial as well much.

In the REPL, y'all can use auto-completion. In the next code fragment, we create a string, mystring, and on the next line we type its proper name followed by hit the <TAB> key twice:

>>> mystring = "Hello world" >>> mystring. mystring.capitalize(    mystring.find(          mystring.isdecimal(     mystring.istitle(       mystring.segmentation(     mystring.rstrip(        mystring.translate( mystring.casefold(      mystring.format(        mystring.isdigit(       mystring.isupper(       mystring.replace(       mystring.carve up(         mystring.upper( mystring.center(        mystring.format_map(    mystring.isidentifier(  mystring.join(          mystring.rfind(         mystring.splitlines(    mystring.zfill( mystring.count(         mystring.index(         mystring.islower(       mystring.ljust(         mystring.rindex(        mystring.startswith( mystring.encode(        mystring.isalnum(       mystring.isnumeric(     mystring.lower(         mystring.rjust(         mystring.strip( mystring.endswith(      mystring.isalpha(       mystring.isprintable(   mystring.lstrip(        mystring.rpartition(    mystring.swapcase( mystring.expandtabs(    mystring.isascii(       mystring.isspace(       mystring.maketrans(     mystring.rsplit(        mystring.championship(

If all went well, you should get a big list of operations that can be performed on a string. You can try some of these yourself:

>>> mystring.lower() 'hello globe' >>> mystring.upper() 'HELLO WORLD'

An caption of each of these operations can be constitute in the official Python documentation, but we'll cover a few here as well.

Getting the cord length

A common operation is to go the string length. Unlike the operations above, this can exist done with Python'south len() role like this:

>>> len("I wonder how long this string will be...") 40 >>> len(mystring) 11

In fact, the len() function can be used on many objects in Python, as you'll learn later on. If functions are new to you, you're in luck, because our next page will explicate exactly what a function in Python is, and how you lot can create one yourself.

Carve up a cord

Some other common operation is splitting a cord. For this, we can use ane of the built-in operations, conveniently called divide. Let'southward start elementary, by splitting upwardly two words on the space character between them:

'Hello earth'.split(' ') ['Hello', 'globe']

The split operation takes one argument, which is the sequence of characters to split on. The output is a Python list, containing all the split words.

Divide on whitespace

A common use-instance is to divide on whitespace. The trouble is that whitespace can exist a lot of things. Iii common ones that you probably know already are:

  • space characters
  • tabs
  • newlines

But there are many more, and to go far even more complicated, whitespace doesn't mean only 1 of these characters, but tin as well exist a whole sequence of them. E.m., three consecutive spaces and a tab grapheme form i slice of whitespace.

Exactly because this is such a common operation amid programmers, and because it'southward hard to do it perfectly, Python has a user-friendly shortcut for it. Calling the split operation without any arguments splits a string on whitespace, as tin be seen below:

>>> 'How-do-you-do \t\due north there,\t\t\t stranger.'.dissever() ['Hello', 'there,', 'stranger.']

Every bit you can see, no matter what whitespace character and how many, Python is still able to split this string for united states of america into separate words.

Replace parts of a cord

Let's look at one more than built-in operation on strings: the replace function. It'southward used to supplant one or more characters or sequences of characters:

>>> 'Hello earth'.replace('H', 'h') 'howdy globe' >>> 'Hello earth'.replace('l', '_') 'He__o wor_d >>> 'Hello globe'.replace('world', 'readers') 'Hello readers'

Reversing a cord

A common assignment is to reverse a Python string. There'southward no opposite performance, though, every bit you might take noticed when studying the list of operations like lower() and upper() that comes with a string. This is not exactly beginner stuff, so feel free to skip this for now if you lot're going through the tutorial sequentially.

To opposite a string efficiently, we can treat a string equally a list. Lists are covered later on on in this tutorial (see for-loop). In fact, y'all could run into a string as a list of characters. And, more chiefly, you can treat information technology as such. List index operations like mystring[2] work simply similar they work on lists:

>>> mystring = 'Hello world' >>> mystring[two] 'l' >>> mystring[0] 'H'

Note that in Python, like in all reckoner languages, we start counting from 0.

What as well works exactly the same as in lists, is the slicing operator. Details of list slicing tin can be establish on the Python listing page and won't be repeated here. If you're coming from other languages, you might compare it to an operation similar substring() in Java, which allows you to recall specific parts of a string.

Slicing in Python works with the slicing operator, which looks like this: mystring[beginning:stop:step_size]. The key characteristic we use from slicing is the step size. Past giving the slicing operator a negative pace size of -i, we traverse the string from finish to beginning. By leaving the start and end position empty, Python assumes with want to slice the unabridged cord.

So we can use slicing to reverse a Python string as follows:

>>> mystring = 'Howdy world' >>> mystring[::-one] 'dlrow olleH'

Python string format with f-strings

A common blueprint is the need to merge some text strings together or use a variable within your string. There are several ways to do and so, simply the most modern way is to utilize f-strings, short for formatted strings.

Let'due south first look at an instance, before we swoop into the details:

>>> my_age = 40 >>> f'My historic period is {my_age}' My age is 40

The f-string looks similar a regular cord with the add-on of an f prefix. This f tells Python to browse the cord for curly braces. Inside these curly braces, we can put any Python expression we want. In the higher up case, we just included the variable my_age. F-strings provide an elegant way of including the results of expressions inside strings.

Hither are a couple more examples you lot can effort for yourself besides, inside the REPL:

>>> f'3 + 4 = {3+4}' '3 + 4 = 7' >>> my_age = twoscore >>> f'My age is, unfortunately, not {my_age-eight}' 'My age is, unfortunately, not 32'

I'm only touching the basics hither. If you're following the tutorial front to back, you tin can go along with the next topic since you know more than enough for now. If you'd similar to find out more virtually f-strings, try the following resources:

  • Official docs on f-strings
  • The official guide has some more examples hither: formatted cord literals

Buy Me A Coffee Cheers for reading my tutorials. I employ ads to go on writing gratis articles, I promise yous understand! Support me by disabling your adblocker on my website or, alternatively, buy me a coffee.

chaceyoultas.blogspot.com

Source: https://python.land/introduction-to-python/strings

0 Response to "Write a Program That Reads in Three Strings and Sorts Them Lexicographically. Python"

Post a Comment

Iklan Atas Artikel

Iklan Tengah Artikel 1

Iklan Tengah Artikel 2

Iklan Bawah Artikel