• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / What Are Strings In Python?

What Are Strings In Python?

Author: PFB Staff Writer
Last Updated: December 2, 2020

What is a string?

A string is a list of characters in order.

A character is anything you can type on the keyboard in one keystroke, like a letter, a number, or a backslash.

Strings can have spaces: “hello world”.

An empty string is a string that has 0 characters.

Python strings are immutable

Python recognize as strings everything that is delimited by quotation marks (” ” or ‘ ‘).

Accessing Strings


Use [ ] to access characters in a string:
word = "computer"
letter = word[0] 

Use [ # :#] to get set of letters
word= word[0:3]

To pick from beginning to a set point:
word = [:4]

To pick from set point to end:
word = [3:]

To pick starting from the end:
word = [-1] 

Quotes


Strings can be enclosed in single quotes
print 'Hello World in single quotes'

Strings can also be enclosed in double quotes
print "Hello World in double quotes"

Strings can also be enclosed in triple quotes
print """ This is a multiline string
Such strings are also possible in Groovy.
These strings can contain ' as well as " quotes """

Strings can be continued on the next line
print "This string is continued on the
next line (in the source) but a newline is not added"

Raw Strings

Raw strings exists so that you can more conveniently express strings that would be modified by escape sequence processing.

This is most especially useful when writing out regular expressions, or other forms of code in string literals.

Concatenate Strings

In Python there are a few different ways to concatenating strings. Concatenation combines two (or more) strings into a new string object.

You can use the + operator, like this:


print "You can concatenate two " + "strings with the '+' operator."
 
str1 = "Hello"
str2 = "World"
str1 + str2    	# concatenation: a new string 

String literals may be concatenated by a space

word = 'left' "right" 'left'

Any string expression may be concatenated by a +


word = wordA + "
" + wordB

Reverse Strings


string = "Hello World"
 
print ' '.join(reversed(string))
>>Output:
d l r o W o l l e H

Changing Upper and Lower Case Strings


string = "Hello World"

print string.lower()

print string.upper()

print string.title()

Replace Strings


string = "Hello World"

string.replace(“Hello”, “Goodbye”)

Repeat Strings


print "."* 10 # prints ten dots( print string * n ; prints the string n times)

Split Strings

Python has a very neat function for breaking up strings into smaller strings.

The split function splits a single string into a string array using the separator
defined. If no separator is defined, whitespace is used.

x = 'blue,red,green'
x.split(",")
['blue', 'red', 'green']

word = "This is some random text"
words2 = word.split(" ")
print words
['This', 'is', 'some', 'random', 'text']

Startswith / Endswith


Checking if a string starts or ends with a substring:
s = "hello world"

s.startswith("hello")
True

s.endswith("rld")
True

Strip Strings

Python strings have the strip(), lstrip(), rstrip() methods for removing any character from both ends of a string.

If the characters to be removed are not specified then white-space will be removed.

string = "Hello World"

#Strip off newline characters from end of the string
print string.strip('
')

strip() 	#removes from both ends
lstrip() 	#removes leading characters (Left-strip)
rstrip() 	#removes trailing characters (Right-strip)
	
spacious = "   xyz   "
print spacious.strip()
 
spacious = "   xyz   "
print spacious.lstrip()
 
spacious =  "xyz   "
print spacious.rstrip()

Slicing Strings

Strings have indices, so we can refer to every position of a string with its corresponding index. Keep in mind that python, as many other languages, starts to count from 0!!

print string[1]	        #get one char of the word
print string[1:2]       #get one char of the word (same as above)
print string[1:3]       #get the first three char
print string[:3]        #get the first three char
print string[-3:]       #get the last three char
print string[3:]        #get all but the three first char
print string[:-3]       #get all but the three last character

x = "my string"

x[start:end] 			# items start through end-1
x[start:]    			# items start through the rest of the list
x[:end]      			# items from the beginning through end-1
x[:]         			# a copy of the whole list

Formatting Strings

Here are a few examples of string formatting in python.

String formatting with %

The percent “%” character marks the start of the specifier.

%s # used for strings
%d # used for numbers
%f # used for floating point

x = ‘apple’
y = ‘lemon’
z = “The items in the basket are %s and %s” % (x,y)

Note: Make sure to use a tuple for the values.

String formatting using { }

The pairs of empty curly braces {} serve as place-holders for the variables that we want to place inside the string.

We then pass these variables into our string as inputs of the strings format() method in order.

With this method, we don’t have to change our integer into string types first the format method does that for us automatically.



fname = "Joe"
lname = "Who"
age = "24"
 
#Example of how to use the format() method:
print "{} {} is {} years ".format(fname, lname, age)
 
#Another really cool thing is that we don't have to provide the inputs in the 
#same order, if we number the place-holders.

print "{0} {1} is {2} years".format(fname, lname, age)

Join Strings

This method takes a list of strings and joins them together with the calling string in between each element.


>>> ' '.join(['the', 'cat', 'sat', 'on', 'the', 'mat'])
'the cat sat on the mat'
 
#Let's look at one more example of using the Join method:
#creating a new list
>>> music = ["Abba","Rolling Stones","Black Sabbath","Metallica"]
 
#Join a list with an empty space
>>> print ' '.join(music)
 
#Join a list with a new line
>>> print "
".join(music)

Testing Strings

A string in Python can be tested for truth value. The return type will be in Boolean value (True or False)

my_string = "Hello World"

my_string.isalnum()			#check if all char are numbers
my_string.isalpha()			#check if all char in the string are alphabetic
my_string.isdigit()			#test if string contains digits
my_string.istitle()			#test if string contains title words
my_string.isupper()			#test if string contains upper case
my_string.islower()			#test if string contains lower case
my_string.isspace()			#test if string contains spaces
my_string.endswith('d')		#test if string endswith a d
my_string.startswith('H')	#test if string startswith H

Built-in String Methods

String methods are working on the string its called from! These are built in String methods. (using dot notation)

>>string.string_method()

string = "Hello World"

To manipulate strings, we can use some of Pythons built-in methods

string.upper() 				#get all-letters in uppercase
string.lower() 				#get all-letters in lowercase
string.capitalize() 		#capitalize the first letter
string.title() 				#capitalze the first letter of words
string.swapcase() 			#converts uppercase and lowercase
string.strip() 				#remove all white spaces
string.lstrip() 			#removes whitespace from left
string.rstrip() 			#removes whitespace from right
string.split() 				#splitting words
string.split(',') 			#split words by comma
string.count('l') 			#count how many times l is in the string
string.find('Wo') 			#find the word Wo in the string
string.index("Wo") 			#find the letters Wo in the string
":".join(string) 			#add a : between every char
" ".join(string) 			#add a whitespace between every char
len(string) 				#find the length of the string
string.replace('World', 'Tomorrow') #replace string World with Tomorrow

Sources
https://github.com/adaptives/python-examples
http://en.wikibooks.org/wiki/Python_Programming

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: PFB Staff Writer

More Python Topics

API Argv Basics Beautiful Soup bitly Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehensions in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Pandas Append Row to DataFrame
  • Convert String to DataFrame in Python
  • Pandas DataFrame to List in Python
  • Solved: Dataframe Constructor Not Properly Called Error in Pandas
  • Overwrite a File in Python

Copyright © 2012–2023 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us