Python Strings is a Datatype. Strings literals (Any constant value which can be assigned to the variable is called literal/constant) in python are surrounded by either single quotation marks or double quotation marks.
'Hello World'
is the same as "Hello World"
Syntax Python Strings
The string can use direct or use a variable like this example.
str1 = "Hello World" str2 = 'Hello World' print(str1) print(str2)
Output: Hello World
Hello World
And Without a variable example
print("Hello World")
Output: Hello World
Python Strings Methods
Here are some of the most common python strings in-build functions :
str.lower()
: Returns the lowercase version of the string
str1 = "Hello World" print(str1.lower())
Output: hello world
str.upper()
: Returns the uppercase version of the string
str1 = "Hello World" print(str1.upper())
Output: HELLO WORLD
str.replace('old', 'new')
: returns a string where all occurrences of ‘old’ have been replaced by ‘new’
str1 = "Hello World" print(str1.replace('Hello', 'Bye'))
Output: Bye World
str.strip()
: Returns a string with whitespace removed from the start and end
str1 = " Hello World " print(str1.strip())
Output: Hello World
str.startswith('eyehunt')
orstr.endswith('eyehunt')
: Tests if the string starts or ends with the given string
str1 = "Hello World, I am Eyehunt" print(str1.startswith('Eyehunt')) print(str1.endswith('Eyehunt'))
Output: False
True
str.find('Hello')
: searches for the given string (not a regular expression) and returns the first index where it begins or-1
if not found
str1 = "Hello World, I am Eyehunt" print(str1.find("W")) print(str1.find("B"))
Output: 6
-1
str.split('delim')
: Returns a list of substrings separated by the given delimiter.
str1 = "Hello World, I am Eyehunt" strSplit = str1.split(",") print(str1.split(",")) print(strSplit[0])
Output : [‘Hello World’, ‘ I am Eyehunt’]
Hello World
str.len()
: The len() method returns the length of a string.
str1 = "Hello World, I am Eyehunt" print(len(str1))
Output: 25
The example of Python string functions – substring, replace, Slicing, splitting, find, formate, join, index and string concatenation follow this tutorial:
- Python String Concatenation | Combine Strings
- Python Join Function | Join Strings
- Python Split() Function | Split String Example
- Python Substring | Slicing & Splitting String | Examples
- Python string index() Function | Get the index of a substring
- Python string replace function | Examples
- Python Format() Function | String Formatting
Do comment if you have any doubt and suggestion on this tutorial.
Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6Python 3.7
All examples are in Python 3, so it may change its different from python 2 or upgraded versions.