Creating a string There are many different ways to create a string The simplest way is to hard code it into your program mystring Hello Remember individual characters of ID: 636372
Download Presentation The PPT/PDF document "Strings in Python Creating a string" is the property of its rightful owner. Permission is granted to download and print the materials on this web site for personal, non-commercial use only, and to display it on your personal computer provided you do not modify the materials and that you retain all copyright notices contained in the materials. By downloading content from our website, you accept the terms of this agreement.
Slide1
Strings in Python
Creating a stringSlide2
Creating a string
There are many different ways to create a string
The simplest way is to hard code it into your program
mystring
= “Hello”
Remember individual characters of
mystring
cannot be changed afterward (strings are immutable)
Many of the string methods return new strings
newstring
=
mystring.upper
()
The typecast
str
will create a string from another data type
mynumstring
=
str
(
num
)Slide3
Getting a string from input
When you read from the keyboard, the input function will always return a string
myname
= input(“What’s your name? “)
When you learn about external files, one thing you do is read from them (see Chapter 10)
The input from a file always comes in as a string or list of stringsSlide4
Other ways to create a string
You can build up a string one character at a time
The pattern is very similar to an accumulator
You initialize a variable to an empty string
new_one
= “”
Then in a loop you concatenate the new character onto the variable
new_one
=
new_one
+
ch