RUVIDEO
Поделитесь видео 🙏

Changing Strings In Python

See our full tutorial on Changing Strings In Python at http://learnpythontutorial.com/changing-strings-in-python/
Changing Strings In Python
Since we starting talking about strings in Python, I always said that strings could not be changed and that they are often referred to as immutable. How do we have a Python tutorial on changing strings in Python then? We are not actually changing the string object itself we need to create a new object. In this tutorial, we will look at how to take the current string and create a new string object. This is the only means to change strings in Python. Remember we are not changing the original string object we are establishing a new string object.

What Happens If We Change a String in Place?

a = 'Cat'
a[0] = 'B'
Traceback (most recent call last):
File "stdin", line 1, in module
TypeError: 'str' object does not support item assignment
In the example above we try to change cat to bat but as you can see we have an error. The last line of the error Python basically tells us what happened. The error states string object does not support item assignment. The only way we could do to change a string is by creating a new string.

Wait doesn't string concatenation enable us to change a string in place? Nope, string concatenation creates a new string object as well.

How Do We Change A String By Creating a New Object?

#Creating a new string from a previous string via concatenation
a = 'Cat'
a = a + ' in a hat'
a
'Cat in a hat'

#Creating a new string from a previous string via slicing and concatenation
b = 'New String'
b = 'This is a ' + b[:]
b
'This is a New String'
Let's take a look at what happened in the example above.

Example 1:

a = 'Cat' - We create a string object('cat') and assign a name to the object(variable) of a.
a = a + ' in a hat' - We take the object('cat') and concatenate a new string(' in a hat') to previous string then we reassign the name(variable) to the new object that now contains a new string object('Cat in a hat')
a - We call the name of a and are returned the new object.
Example 2:

b = 'New String' - We create an new string object('New String') and assign the name(variable b) to the new object.
b = 'This is a ' + b[:] - We create a new object('This is a ') and concatenate a sliced version of previous string object('New String') and now we have created a new string object and assign the previous name(variable) to the new object.
b - We call the new string object and we get 'This is a new string' returned to us.
Python String Method .replace()

We haven't used any string methods yet but will cover them all throughout our next several tutorials. This string method gives us the ability to change an existing string but we still need to establish a new object. Check out the example below.



a = "Python"
a = a.replace('ython', 'rogramming')
a
'Programming'
What happened in the above example?

a = "Python" - We first create a string object("Python") and assign a name(variable) to the object
a = a.replace('ython', 'rogramming') - We use the .replace() method to find a portion of our string and replace with a new string. First argument in the replace method is find and the second argument is content we want to use to replace. Now we have created a new string object and assigned the name(variable a) to the new string.
a - We then call the variable and we are returned the new String object of 'Programming'
Conclusion
How To Change A String in Python

In this tutorial changing strings, in Python we took a look at few avenues we have to change a string in Python but they all create new string objects so we are not actually changing the original string object. There are a few more methods we can use to change a string and we will cover them in the upcoming tutorials.

Что делает видео по-настоящему запоминающимся? Наверное, та самая атмосфера, которая заставляет забыть о времени. Когда вы заходите на RUVIDEO, чтобы посмотреть онлайн «Changing Strings In Python», вы рассчитываете на нечто большее, чем просто загрузку плеера. И мы это понимаем. Контент такого уровня заслуживает того, чтобы его смотрели в HD 1080, без дрожания картинки и бесконечного буферизации.

Честно говоря, Rutube сегодня — это кладезь уникальных находок, которые часто теряются в общем шуме. Мы же вытаскиваем на поверхность самое интересное. Будь то динамичный экшн, глубокий разбор темы от любимого автора или просто уютное видео для настроения — всё это доступно здесь бесплатно и без лишних формальностей. Никаких «заполните анкету, чтобы продолжить». Только вы, ваш экран и качественный поток.

Если вас зацепило это видео, не забудьте взглянуть на похожие материалы в блоке справа. Мы откалибровали наши алгоритмы так, чтобы они подбирали контент не просто «по тегам», а по настроению и смыслу. Ведь в конечном итоге, онлайн-кинотеатр — это не склад файлов, а место, где каждый вечер можно найти свою историю. Приятного вам отдыха на RUVIDEO!

Видео взято из открытых источников Rutube. Если вы правообладатель, обратитесь к первоисточнику.