Link Search Menu Expand Document

Module 04. Strings

Lecture Date: September 13, 2021 - Monday Slides

DataCamp DataCamp Chapter: Introduction to Python -> Functions and Packages (partly match)

In this Python lecture, we will talk about strings, which is a variable type that can hold text type of information in it.

1. Strings

Download code

1.1. Getting Started with Strings

Creating a string

'A string'
'A string'

Assigning a string to a variable

str1 = 'Hello'
str2 = 'world'

Mixed quotation error

str3 = 'hello"
  File "<ipython-input-3-4db33dfe5244>", line 1
    str3 = 'hello"
                  ^
SyntaxError: EOL while scanning string literal

Getting user input

username = input("Your name:")
print(username)
Your name: Hamdi


Hamdi

Converting user input to number

age_as_string = input("Your age:")
age_as_number = int(age_as_string)
Your age: 11

Converting bad user input to number

age_as_string = input("Your age:")
age_as_number = int(age_as_string)
Your age: 22

1.2. Some string operations

Concatenation

str1 = 'Hello'
str2 = 'world!'
greeting = str1 + str2
print (greeting)
Helloworld!
str1 = 'Hello'
num = 11
result = str1 + num
print (result)
---------------------------------------------------------------------------

TypeError                                 Traceback (most recent call last)

<ipython-input-9-fa647a173fc5> in <module>
      1 str1 = 'Hello'
      2 num = 11
----> 3 result = str1 + num
      4 print (result)


TypeError: can only concatenate str (not "int") to str

* operator

print('a'*3)
aaa
num = 16
char1 = '~'
print(char1*num)
num = int(num / 2)
print(char1*num)
num = int(num / 2)
print(char1*num)
num = int(num / 2)
print(char1*num)
num = int(num / 2)
print(char1*num)
~~~~~~~~~~~~~~~~
~~~~~~~~
~~~~
~~
~

1.3. Printing strings

dept = 'CDS'
school = 'GMU'
semester = 'spring'
year = 2020
print(dept,school,semester,year)
CDS GMU spring 2020
print(dept + school + semester + str(year))
CDSGMUspring2020
print(f'{dept} dept at {school} welcomes {semester} {year} semester')
CDS dept at GMU welcomes spring 2020 semester

1.4. Indexes, slicing, and length

indexing

name = 'Jacob'
name[2]
'c'
i = 3
name[i]
'o'
name[5] # when you go out of range
---------------------------------------------------------------------------

IndexError                                Traceback (most recent call last)

<ipython-input-21-a171664f686e> in <module>
----> 1 name[5] # when you go out of range


IndexError: string index out of range

length

uni = 'George Mason University'
len(uni)
23

slicing

uni[0:6]
'George'
uni[:6]
'George'
uni[5:]
'e Mason University'
uni[-1]
'y'
uni[-5:]
'rsity'

type check

name = 'Jacob'
print(type(name))

name = 111
print(type(name))
<class 'str'>
<class 'int'>

1.5. in operator

fruit = "banana"
print("b" in fruit)
True
print("baba" in fruit)
False

1.6. comparisons

fruit == "banana"
True
fruit < "cucumber"
True
fruit > "green"
False
fruit < "apple"
False

1.7. string functions

s = "Hello World"
print(s.lower())
hello world
dir(fruit)
['__add__',
 '__class__',
 '__contains__',
 '__delattr__',
 '__dir__',
 '__doc__',
 '__eq__',
 '__format__',
 '__ge__',
 '__getattribute__',
 '__getitem__',
 '__getnewargs__',
 '__gt__',
 '__hash__',
 '__init__',
 '__init_subclass__',
 '__iter__',
 '__le__',
 '__len__',
 '__lt__',
 '__mod__',
 '__mul__',
 '__ne__',
 '__new__',
 '__reduce__',
 '__reduce_ex__',
 '__repr__',
 '__rmod__',
 '__rmul__',
 '__setattr__',
 '__sizeof__',
 '__str__',
 '__subclasshook__',
 'capitalize',
 'casefold',
 'center',
 'count',
 'encode',
 'endswith',
 'expandtabs',
 'find',
 'format',
 'format_map',
 'index',
 'isalnum',
 'isalpha',
 'isascii',
 'isdecimal',
 'isdigit',
 'isidentifier',
 'islower',
 'isnumeric',
 'isprintable',
 'isspace',
 'istitle',
 'isupper',
 'join',
 'ljust',
 'lower',
 'lstrip',
 'maketrans',
 'partition',
 'replace',
 'rfind',
 'rindex',
 'rjust',
 'rpartition',
 'rsplit',
 'rstrip',
 'split',
 'splitlines',
 'startswith',
 'strip',
 'swapcase',
 'title',
 'translate',
 'upper',
 'zfill']
"   aaa aaa ".strip()
'aaa aaa'

Back to top

Copyright © Hamdi Kavak. CDS 230 - Modeling and Simulation 1.