Python Tutorial for Beginners 2: Strings – Working with Textual Data

Hey there. How’s it going everybody in this video? We’ll be learning about python Data types and specifically We’ll be learning about how to work with textual data and textual data in python are represented with strings So we currently have [opened] our intro pi file that we were working with in the last video Where we just printed out hello world and I’ll go ahead and run this so that we can see that down here It does print out hello [world] [now] This line here is using the print function and we’re passing this text value into that print function now if we wanted to create a Variable that holds that text value then we could say now I’ll just get rid of this comment for now So if I wanted a variable to hold that value then I can just create a variable and we’ll call that message and we’ll set that message variable equal to our text value that we passed in to print and Here message is our variable [name] so if you’re coming from another [language] Then you might be wondering if we need [to] use semicolons or something like that to end each line but python doesn’t need that it operates on Whitespace alone Which makes it a very clean language to work with? Now by convention our variables are usually all lowercase and if it’s multiple words then we separate those with underscore So if instead my variable name was my message, then it would be my underscore message So that’s just a convention that’s commonly used and also these variable names should be as descriptive as possible As to what values they’re meant to hold so message is a good variable name here because it’s holding our message But if I was instead to call this variable m which is a valid variable name But anyone reading my code now wouldn’t know when they see this in variable What value it’s supposed to hold so message is a much better variable name in this case So this message variable now holds our text data and our text data is called a string now We can use our variable in place of this string Anywhere that we use it in our program, so instead [of] printing out hello world Directly here. I’m instead going to now print out this variable and that should give us the same results So if I run that then you can see down here, we still get [the] same result now We can see that I created this string with single quotes now you can also use double quotes so if you’re wondering if there is a difference between the single quotes in the double quotes And it really just depends on what text you have in your string So for example if you have a single quote in your string So for example let’s create one with a single quote instead of hello world, [I] will instead make our string Bobby’s World Now see the problem [here] is that? Python sees this single quote within our text as being the end of the string and it’s not going to know what to do With what comes after that single quote here because it thinks that’s where the string is closing So if you run this now then you’ll get an error now There’s a couple of different ways to [handle] this we could escape this single quote with a backslash so if I escape that single quote and now Run this now python knows that this single quote doesn’t close out the string and that instead this one should Now another way to handle that is [to] instead So I’ll take away that xscape character now another way to handle that is instead Just use double quotes on the outside of our string any string [that] contains single quotes So if we know that our string contains a single quote then we can instead use double quotes on the outside And then it’ll know that that single quote isn’t the end of the string so now if we run this then we can see that It still works fine But that doesn’t necessarily mean that double quotes are better because it goes both ways if your string contains double quotes in the message then I would use single quotes on the outside now if we needed to create a multi-line string and one way we can do this is by using three quotes at the beginning and end of our string and these can also be Single or double quotes as [well], so let’s go ahead and look at an example So I’ll add three quotes to the beginning and end of our string here And now I’ll just add [some] text to spans multiple Lines here so I’ll just say was a good and then hit enter to go to a new line and say cartoon in the 1990s so now if we run [that] and we can see that it printed out [our] string correctly over multiple lines, [okay]? So let’s go back to our simple hello world example So I’m just going to take all of that and replace it with our previous Hello world example, and now let’s go ahead and just run that really quick So we’re back to our starting point so we can think of our string as a string of individual characters And we can access these individual characters also, so first let’s see how we can find how many characters are in our string So to do this we can use the [len] function which stands for length So whenever I print out here if I was instead of printing my message if I was to print out this Length function and pass in message, and then run this. Now we’re no longer printing out our message We’re printing out the length of our message And we can see that it says that the length of our string is 11 And if we counted these up 1 2 3 4 5 6 7 8 9 10 11 Then we can see that that’s correct, and we can access our strings characters individually, so to do this we can use the square Brackets after our string and pass in the location of the character that we want. So, I’ll say print Message and then square brackets now the location is called an index and it starts out at 0 So to access the first character of our string we can say print the message and then access this index of 0 so if we print that then we can see that we got the capital H now since the length of our string is 11 that means that with the first character starting out at 0 our last character would be at Index 10 so it’s our total length minus 1 so if I was to say print out the Location at Index 10 the value at Index 10 then we can see that we got our d character Which is the last character in that string. Now if you accidentally try to access an index that doesn’t exist then you’ll get an index error. So if we were to say Access the index of 11, and we can see that that through an index error now We can also access a range of characters So if I just wanted to get the word hello from our string then we could say that we want 0 and then this colon 5 and we’ll explain this So the first index here is our starting point and the second in that index which is separated by this colon is The stopping point now one thing a little confusing about this is that the first index is Inclusive which means it’s going to include that value, but the second index is not now There’s good reasons for this But it’s still easy to forget so basically what we’re saying is I want all the characters Between the beginning and up to but not including the fifth index And it will be more clear if we just go ahead and run this so we can see that it prints out. Hello So it printed out our message from the zero index here all the way up to but not including The [5th] Index here, so we got hello now since our starting point. Here is just [the] first index We can actually just leave that off and it will assume that we want to start at the beginning So if we don’t put anything there and then : [five] then we should get the same thing So if we run [that] we can see we still got hello now instead if we wanted to grab the word world from the string then we could start at The sixth Index and then we can just go to the end and just like leaving off our Starting index it will start from the beginning Leaving off the stop index just goes all the way to the end So now if we run that and we can see that it gives us back the word world now what we’re doing Here is called slicing and if you’d like to learn more about Slicing in depth then you can watch my detailed video on that and I’ll leave a link to [that] in the [description] section below So now let’s just go back to printing out our message and let me run this okay So all of the data types that we’re going to review are going to have certain methods available to us that give us access to a lot of useful functionality now when I say methods a lot of people wonder what’s the difference between a method and a function and functions and methods are basically the same thing [a] Method is just a function that belongs to an object It’s not important to get into the details of that now But if you hear me say method or function then you can basically think of those as the same thing for now So like I was saying the data types that we’ll be going over all have certain methods Available to us that give us access to a lot of useful functionality so let’s look at some of these string methods So we can see here that our hello world text is Capitalized, but let’s say [that] we wanted that to be all lowercase now to do this It’s just as easy as saying print message and then to lowercase this we can say dot lower Now when we run this dot lower with these parentheses here. That’s running the lower method on the string So when we ran that we can see that now our hello world has been set to all lowercase [and] [if] we wanted to do this to uppercase and it’s as easy as changing at Lower to upper if we run that now we can see that Hello
World is all uppercase? So now let’s say that we want to count a certain number of characters in our string and to do that We can use the count method and the count method actually takes a string as an argument so we can say Message dot count and now we have to pass in an argument And it has to know what we want to count in our message So what for now? We’ll [just] say count hello And if we run that we can see that it returns that the string hello appears in our message one time But if we instead just passed in a single character as argument So I’ll pass in an L if I run that You can see that we get a 3 because there are three L’s and our message variable So if we instead want to find the index of where certain characters can be found and we can use the find method so I? Could come up here instead of saying dot count I can say not fine and now this takes an argument as well It’s what we want to find so let me type in world here and run this And we can see when [we] run this that it returns a six and that’s because world starts at the sixth index of our message variable now if we try to Find a string of characters that doesn’t exist then it will just return negative one so if instead of world I typed in universe and ran that you can see it returns a negative one because it can’t find that anywhere in our message variable Okay, so now let’s say that we want to replace some characters in our string with some other characters And we can do this with the replace method now first. I’m going to change this change this back to printing out our regular message [so] I’ll just delete these Now let’s try to use our replace method right below where we first set our message fair herbal and this method takes two arguments First it takes what we want to replace so first let me just say message But replace so first it takes what we want to replace, so let’s say that we want to replace world and now the second argument Which is separated by a comma [is] what we want to replace world with so we’ll replace world with universe So now if [we] run this and this might be a little unexpected we can see that it’s still printing out hello world [now] the reason our replacement didn’t work is because it’s not making that replacement in place It’s actually returning a new string with those values replaced and we’ll learn more about return statements when we learn about Functions, but basically we need to set a new variable here To get that returned string with those replacements, so I could say something like new message is equal to That original method with this replacement So now if we set that New variable and instead print that new message and run that and you can see that now it replaced the world with universe and if you really wanted to make the Replacement to the message variable then instead of making a new message variable and we can just set this same message Variable again, so now we’re setting the same message variable equal to that replacement and then printing it out So if I run that and we can see that now the message variable had world Replaced with universe and this may look a little strange [to] set a variable to an altered [version] of itself But it’s very common, and you’ll be using that a lot Okay, so now let’s get rid of this replace line here And now let’s look at how we can add multiple strings and concatenate them together, so instead of saying hello world I’m instead just going to set this equal to hello and Instead of calling this message. I’m going to set this equal to greeting and just below greeting I’m going to create a variable called name and I’m going [to] set that equal to we’ll just say Michael and now lastly let’s create a message here and We want this message to combine our greeting with our name Wanted to say hello Michael and one way to do this is to use the plus sign operator so We could try this by saying greeting plus name now if we run this and we can see that It’s not exactly what we wanted it combined them together, but it doesn’t have a space there So when you’re concatenated strings together it’s easy to make mistakes like this So what we want to do is add a string between them so that spaces them out so we can add a string between these Just by putting in a string literal here And I’m also going to put in a comma and a space to separate those and now we also need another plus sign So that we’re adding the name after that string so now we’re saying that we want this greeting. Which is hello plus this comma and space plus the name so if I run this Then we can see that it concatenated those strings together How we wanted now sometimes using the plus sign isn’t the best way to go if we wanted to create a longer more? Complicated string while using our variables and adding them all together like this Might get hard to keep track [of] so let’s say that we wanted to add to the end of our message Just by you know closing off a sentence and saying Welcome so to do that after our name variable we could add another string that is a period to close off that sentence a space and then Welcome with an exclamation point so let’s go ahead and run that now we can see that it printed out the string How we wanted it to look? But it’s starting to get a little complicated on this line here to keep track of all of our plus signs and spaces within our message instead with strings like this It’s usually better to use a formatted string [this] allows [us] to write the sentence as it will appear and put placeholders in place of our variables So let’s go ahead and see what this would look like so though instead use a formatted string We can say message is equal to and we’re just going to write it exactly how it appears Except everywhere where we want to Replace with a variable we’re going to put in a placeholder and those placeholders are going to be these curly brackets so we want a placeholder for the greeting and then a comma a space and a placeholder for the name [and] a period and then [we’ll] type out welcome and an exclamation point and now to fill those placeholders with our variables We can say dot format And pass in greeting for the first placeholder and [then] name for the second place holder So now let’s go ahead and delete this line where we where we were using the plus sign Operator so if we run this we can see that We got the same [thing] as when we concatenate and then together but with longer more complicated strings This is actually a little bit easier to read it might look a little confusing now Since we’re just seeing these placeholders for the first time but after you get used to this you will realize that this is Easier than keeping track [of] all those concatenations and using [stream] formatting like this also gives us some extra Functionality and if you want to see everything [that] you can do with that and I do have a detailed in-depth video on string Formatting and I’ll add that to the description section below Ok and lastly if you’re using python 3.6 or above then you’ll have access to these new things called f strings now if you aren’t using [3.6] or higher then these aren’t going to work because they were only Recently released and not a lot of people are using these f strings yet But I’m really liking them so far Basically the idea behind f strings was to make string formatting as simple as possible So let’s go ahead and see what these look like so to say that [we] want this to [be] an f string We can just add an f right here to the beginning on the outside of the string now instead of using this dot format method well instead just write the variables directly within the placeholders so [I] can remove that dot format method and now we can pass the variables directly within the placeholder So we’ll pass Greeting to that Placeholder and name to that one so I can save that and run it and you can see that using that we got the same Result [and] like I said these f strings are pretty new to the language so even people who are very familiar with python May be seeing this for the first time now one reason I really like these f strings is because you can actually write code within the placeholder So if I wanted the name and all caps for some reason then I could just come [into] the placeholder [here] And say name dot upper and run that directly within the placeholder if I run that Then you can see that now our name was capitalized, okay? So we’re almost finished up But I wanted to show you one last trick here when you’re learning something new in python So [we] saw a lot [of] different methods that we could use on our strings now if we ever wanted to see everything That’s available to us then there are a couple of things that we can do so first we can use this dir function and that looks like this and what this does is if we pass in A Variable then it will show us all of the attributes and methods that we have access [to] with [that] variable now Don’t worry about all of these double underscore methods yet, but if we look down here Then we’ll see a couple of familiar methods that we used in this video [so] for example we have dot upper here we have not replace dot lower So this kind of gives you a broad overview of all the attributes and methods that are [available] to you now This doesn’t show what any of these actually do so to see more information about these string methods Then we can use the help function But if we run this help function on the name then that won’t work we actually need to run it on the string class Itself so we’ll just type in help and then Str for string and if I run that and we can see that this gives us a lot more [information] And I’ll pull this up here a bit so it You know tells us everything that’s available to us, and if I scroll down here [a] bit And if I try to find something that we actually used in this video okay, so we have fine here So you can see that actually gives us a description of what these methods do and what arguments they take Now if you know that you had a certain method available to you But you couldn’t remember exactly what it does then you can actually pass it directly in to help also, so if I wanted to Find out some more information about the lower method then we could say string dot Lower and if we run that and we can see that it gives us information and the description just of what lower does so using that dir function and that help function is a great way to get a broad overview of the methods and attributes that [are] available to you and Also, what using the help function gives you an idea of what those? Methods do without actually you know going online and checking everything there, okay? So I think that is going to do it for this video I hope that now you feel comfortable with Working with strings and are familiar [with] some of the useful things that we can do with those in the next video We’re learning how to work with numbers in python and specifically integers and floats But if anyone has any [questions] about what we covered in this video Then feel free to ask in the comment section below and I’ll do my [best] to answer those if you enjoy these tutorials and would Like to support them then there are several ways [you] can do that The easiest ways to simply like the video and give it a thumbs up and also it’s a huge help to share these videos with Anyone you think would find them useful and if you have the means you can contribute through patreon And there’s a link to that page in the description section below be sure to subscribe for future videos and thank you all for watching you

100 thoughts on “Python Tutorial for Beginners 2: Strings – Working with Textual Data”

  1. I have a problem with replace method…
    String = "Hello, Someone"
    name = input() #John
    String = String.replace("Someone", name)
    #But output is "Hello, Someone"
    #Expected "Hello, John"
    Anybody here to help??

  2. Hy man i just 200dollar to learn python but they don't teach properly but watching your videos help me understanding very wall thanks man for creating these.your videos help me a lot

  3. Sweet! Doing the 100daysofcode "challenge", in preparation for my new education in about 7 months. Gonna go through this tutorial until the book I rented at my library comes in.

  4. Hey Corey, first of all thanks a lot for all your great tutorials. Really helpful! I also wanted to let you know that I just published a tutorial on my own blog on the removal of blank newlines in strings. Since this video is a great fit, I added it as further resource (hope that's fine for you). In case you want to check out the tutorial, you can find it here: Thanks again, and keep on going!

  5. Thank you Corey Schafer, I thought I had wrote another comment mentioning about some sort of bug that i came across, although I believe I had found the root of the bug in my old sloppy code.
    I have grown fond of this .find function, and will use it more often.

  6. Hi everyone. I got some issue with f string. I'm getting an error: SyntaxError: invalid syntax. Python version is 3.7.1 and when I run the code through the terminal f string is working. Could it be something with the settings of my editor? I use Atom. Here is the code itself.
    greeting = 'Hello'
    name = 'Michael'
    farewell = 'Good luck!'
    mes = f'{greeting}, {name}. Welcome! {farewell}'
    Btw the same issue with help(str) method. the error is: AttributeError: 'module' object has no attribute 'help'
    but it runs without any error in terminal.

  7. On mac sublime text (3.1.1) gives error ValueError: Zero length field name in format for the .format example. same code works fine in Idle app – any idea where to look?

  8. Thank you for the work that you are doing I am learning slowly, but am still scratching my head, but that said keep watching and practicing and I will get there an I hope that one day I will get my break as a junior python programmer, as that is what I want to do. BIG THUMBS UP….

  9. The F-string thing isn't working for me. I'm putting in this

    language = "python"
    version = "3"
    message = f'I am learning {language} {version}'


    and getting this error message

    message = f'I am learning {language} {version}'
    SyntaxError: invalid syntax

  10. Kübra Tokuc
    vor 1 Minute
    I've installed python 3.7.2 but i still get a syntax error executing the f-string in sublime text.
    when i run on terminal with python3, it works.
    Do you know what the problem might be?

    btw: great tutorial, thank you

  11. Corey, the triple quotes for a continued string aren't working for me. My text editor is geany. Could this be my problem?

  12. Sorry, I'm new on this program. You have finished the video number 1 with Idle. This number 2 video starts on a different format. How can I work with the same format that you are working?

  13. I really wish coding was taught in some sort of context. Maybe building an app or a stock market system or website etc. I feel i'm learning things but can't imagine for one moment how spending 10 mins learning how to put something in upper and lower case will ever be an essential piece of information i would ever use in a real world project. I mean i'm sure there is a use but there is no context to the learning. Not Corey's fault, just a comment on how coding is taught generally.

  14. Great! I am referring to “Learning Python: Powerful Object-Oriented Programming” by Lutz M (Shroff

    publishing Fifth edition) for Python and your videos seem to cover each and every topic of this book. Can you please suggest which other books to follow for Python?

  15. One more way to format a string :

    greeting = 'Hello'

    name = 'Michael'

    message = '%s, %s. Welcome!' % (greeting, name)


  16. Hey, thanks for these complete introduction videos to Python.
    Please, add the context topics in descriptions!
    I know some python, and I'm trying to learn some more, but I don't want to watch everything all over again!
    Again, thanks for all the great content.

  17. Day:2
    Time: 00:42

    #To Print Message

    print("Hello World")

    #To Provide message

    message="Hello World"


    #To replace the message

    message=message.replace('Hello', 'Hi!')


    #To Print Message from lower to upper


    #To Print message from Upper to Lower


    #Unknown Code



    #To print the place of the word



    #TO provide value to a variable

    x= 32


    #To make calculation





    #Adding 2 strings



    message = greeting + ', '+ name + ' Welcome'


    #Adding string using f strings

    message = f'{greeting},{name.upper()}. How are you?'


    #Everything 'bout strings


    #To view Awesome Attributes


  18. Everytime, I watch your video, I learn new things and it increases my confidence. The way you teach is really effective.You are a great tutor.

  19. Hey Corey,, f string is not working for me. python version installed in my system is 3.7.3. please help

  20. The Python Cheat Sheet you need for Learning and Remember Python Basics is Down Below:

    Hope you will Have a Great Day!!!

  21. I was playing with the len function and i discovered that i can add text in the same line with the results of the len function !
    Example : variable_one = "youtube"
    print(len(variable_one), "so many characters it has") . After the closing parenthesis, you must add a comma then open the quotes, write your text and close the quote and then close the last parenthesis.

  22. 11:47 you say it returns a new string with those values replaced…here 'those' stands for which values…and where are they replaced.

  23. Hey Corey thanks for all your help. I see that you are using the script package when testing, my Mac appears to always default to python2.7. anyway to fix that

  24. I've been waiting soooooo much for people whom explained python to me as well as you do. Ur an absolute beast

  25. Hi, I am super new to the programming world.When I type F in f string method (I'm following all the structures on video), it turns to blue italic f and I face an error when running the command. any idea why?

  26. Hello, Thanks a lot.
    would you please let me know what to understand from below. I am not getting that.

    "lower(self, /)"

    Return a copy of the string converted to lowercase.

  27. Great content, very very helpful video 🙂 Really loved the way you explain things. Thank you so much Corey!!!!!!!!!!!!!!!!!!

  28. string replacement topic is totally skipped by corey becs this uis a very important topic in python why u cannot replaced string with new values Most Fundamental type in Python are Immutable object

    numbers string and Tuples

    Mutable Object include

    list Dictionaries other object depending upon thoer implementation and variable reference subject this is a kind of misleading to the user

  29. why is my f turning yellow when I'm trying to use the new f string method? Might it be i didn't install it right?

  30. If i only discovered you sooner
    screw Udemy , i'm really loving your teaching style so informative and comfortable with no eeh….ahhh.
    Thank you and YT

  31. Very efficient and useful. After a long survey of python learning materials and classes I am so happy to find this channel.

  32. I was also watching udemy or sth, the guy explained the same things in 2 chapter that you explained in 2 mins, very useful videos. Thanks Corey !!

  33. a='Apples','oranges','Tom Thumb','But Python programming is so much better for you.'

    # None Formatted String Example:

    print('My name is '+(a[2])+'. '+(a[0])+' are good for you. So are '+(a[1])+'. '+(a[3]))

    # Old Fashioned/Old School Formatted String Example:

    '''Note: This format example is still around, but (f') format is now the standard in Python 3'''

    print('My name is {}. {} are good for you. So are {}. {}'.format(a[2],a[0],a[1],a[3]))

    # New Formatted String Example:

    print(f'My name is {a[2]}. {a[0]} are good for you. So are {a[1]}. {a[3]}')

    a,b,c,d='Apples','oranges','Tom Thumb','But Python programming is so much better for you.'

    # None Formatted String Example:

    print('My name is '+(c)+'. '+(a)+' are good for you. So are '+(b)+'. '+(d))

    # Old Fashioned/Old School Formatted String Example:

    '''Note: This format example is still around, but (f') format is now the standard in Python 3'''

    print('My name is {}. {} are good for you. So are {}. {}'.format(c,a,b,d))

    # New Formatted String Example:

    print(f'My name is {c}. {a} are good for you. So are {b}. {d}')

  34. # [::-1] can make print text and strings come out backwards

    # .title()
    makes all the words become (title-case) words.
    '''Note: .title() works with reversed text, but it doesn't reverse the first letters of any words.
    The last letters of any words become (title-case), .title[::-1] instead. Example: Backwards is Sdrawkcab '''

    print('this message is backwards. can you read "racecar"?'[::-1].title())

    reverse='this message is backwards. can you read "racecar"?'[::-1].title()


  35. Einstein='infinity'

    # Old Fashioned/Old School Formatted String Example:

    # Title-Case is .title() Upper-Case is .upper() Lower-Case is .lower()

    print('the universe is {}'.format(Einstein).title())

    print('the universe is {}'.format(Einstein).lower())

    print('the universe is {}'.format(Einstein).upper())

    # New Formatted String Example:

    print(f'the universe is {Einstein}'.title())
    print(f'the universe is {Einstein}'.lower())
    print(f'the universe is {Einstein}'.upper())

  36. Python is an easy to learn, powerful programming language. It has efficient high-level data structures and a simple but effective approach to object-oriented programming. Python’s elegant syntax and dynamic typing, together with its interpreted nature, make it an ideal language for scripting and rapid application development in many areas on most platforms.

    The Python interpreter and the extensive standard library are freely available in source or binary form for all major platforms from the Python Web site,, and may be freely distributed. The same site also contains distributions of and pointers to many free third party Python modules, programs and tools, and additional documentation.

    The Python interpreter is easily extended with new functions and data types implemented in C or C++ (or other languages callable from C). Python is also suitable as an extension language for customizable applications.

    This tutorial introduces the reader informally to the basic concepts and features of the Python language and system. It helps to have a Python interpreter handy for hands-on experience, but all examples are self-contained, so the tutorial can be read off-line as well.

    For a description of standard objects and modules, see The Python Standard Library. The Python Language Reference gives a more formal definition of the language. To write extensions in C or C++, read Extending and Embedding the Python Interpreter and Python/C API Reference Manual. There are also several books covering Python in depth.

    This tutorial does not attempt to be comprehensive and cover every single feature, or even every commonly used feature. Instead, it introduces many of Python’s most noteworthy features, and will give you a good idea of the language’s flavor and style. After reading it, you will be able to read and write Python modules and programs, and you will be ready to learn more about the various Python library modules described in The Python Standard Library.

  37. Very good tutorial for people strarting out. The F string was also something I never used before and it's great! Thanks a lot.

  38. 15:35 i learned in "Python the hard way" book that we can use %s %d %r or %f it looks like this:
    print("%s, %s. Welcome!" % (greeting, name))
    but your way looks more neat actually.

    thanks 4 video

Leave a Reply

Your email address will not be published. Required fields are marked *