Split, Join, and Slices Converting tuples and lists to strings


Download 0.69 Mb.
bet3/5
Sana26.01.2023
Hajmi0.69 Mb.
#1128869
1   2   3   4   5
Bog'liq
Split, Join, and Slices

If we don’t specify a separator sequence for split, it’s going to split based on any length of whitespace. This is quite handy, because we know that whatever we get back, we’re not going to have to bother stripping it. The user could enter something like this:

If we don’t specify a separator sequence for split, it’s going to split based on any length of whitespace. This is quite handy, because we know that whatever we get back, we’re not going to have to bother stripping it. The user could enter something like this:

And we’d still get a list like this:

We don’t always need to call split. If we just want to put every character as a different item in a list or tuple, we can just pass the string to the list or tuple function instead:

The newline character

The newline character

​​One thing you may be wondering is, how do we tell the computer that we should have a line break?

There’s actually an invisible character that gets added when we mark the end of a line by pressing “Enter”. If you go into a word processor, and you press “Enter” to go to the next line, what happens when you press “Backspace”? We delete something, and that gets us back to the previous line. What you’ve deleted is the newline character which marks the end of the line.

In Python, we represent this character as \n, and we can use it in strings just like any other character. For example, I can write a string like this:

Here I’ve added two line breaks after the title of some program, and then information about the program author. The output will look like this:

Here I’ve added two line breaks after the title of some program, and then information about the program author. The output will look like this:

If we want to, we can join strings using this character, and it’s possible to split strings using \n as well, but this isn’t really useful for user input. It can, however, be very useful when working with files, which is something we’re going to cover next week.


Download 0.69 Mb.

Do'stlaringiz bilan baham:
1   2   3   4   5




Ma'lumotlar bazasi mualliflik huquqi bilan himoyalangan ©fayllar.org 2024
ma'muriyatiga murojaat qiling