Learning Python: Strings in Python
Strings in Python can be enclosed in either single or double quotes:
'Hello' "Hello"
Concatenating strings can be done by using + operator:
greeting = "Good" + " Morning"
The above expression can also be done using +=:
greeting = "Good" greeting += " Morning" print(name) #Good Morning
the str() function can be used to convert a number for example, into a string:
str(1) #"1"
Python also supports multiline strings. In order to have a multiline string, you need three quotes (either single or double):
print('''Hello
World
!
''')
print("""Hello
World
!
""")
Python also has built-in string functions:
isalnum()- Checks if a string is not empty and has characters or digits.isalpha()- Checks if a string is not empty and has only characters.isdecimal()- Checks if a string is not empty and has digits.upper()- Make a string uppercase.lower()- Make a string lowercase.isupper()- Checks to see if a string is uppercase.islower()- Checks to see if a string is lowercase.title()- Make a string with title case capitalization (e.g. hello world => Hello World).startswith()- Checks a string to see if it starts with a particular substring.endswith()- Checks a string to see if it ends with a particular substring.find()- Find the position of a substring in a string.replace()- Replaces a portion of a string.join()- Add letters to a string.split()- Split a string using a specific character as a separator.strip()- Remove whitespace from a string.
This blog post was originally published on my blog Communicode, where I write about different tech topics.