However, in the second example, we try to use single quotes. ![]() Hence, there’s no problem with the single quote in the word it’s. In the first example below, we use double quotes. So why does it support both? It’s because it allows you to use strings that contain a quote. It looks clearer, and Python tries to be as clear and well-readable as possible. You must press shift with this key to get a double quote.Īs you can see from its answer, Python itself seems to prefer single quotes. The character is often found next to the enter key on your keyboard (US keyboard layout) or on the 2 key (UK layout). Note that these are not two single quotes next to each other. We’ve used single quotes, but Python accepts double quotes around a string as well: > "a" + "b" 'ab' Code language: Python ( python ) If you want to remove parts of a string, there are other methods that you’ll learn about later on. The minus operator doesn’t work on a Python string and produces an error. ![]() The multiplication operator repeats our Python string the given number of times.The plus operator glues two Python strings together.TypeError: unsupported operand type(s) for -: 'str' and 'str' Code language: Python ( python ) Try it with the following expressions: > 'a' + 'b' 'ab' > 'ab' * 4 'abababab' > 'a' - 'b' How to create a Python stringĪ Python string needs quotes around it for it to be recognized as such, like this: > 'Hello, World' 'Hello, World' Code language: Python ( python )īecause of the quotes, Python understands this is a sequence of characters and not a command, number, or variable.Īnd just like with numbers, some of the operators we learned before work on Python strings, too. ![]() Now that we know a string, we’ll look at how to create one. It’s a well-known term in computer science and also means the same thing in most other languages. In even simpler terms, a string is a piece of text. The following is a formal definition a Python string: String A string in Python is a sequence of characters
0 Comments
Leave a Reply. |
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |