Difference between revisions of "Python: String Operation"

From OnnoWiki
Jump to navigation Jump to search
(Created page with " ==Strip /n== line.strip() will remove all types of whitespaces from both ends of the line. You can use line.rstrip("\n") to remove only the trailing "\n". ==Join Line==...")
 
Line 4: Line 4:
 
==Strip /n==
 
==Strip /n==
  
line.strip() will remove all types of whitespaces from both ends of the line.
+
* line.strip() - remove all types of whitespaces from both ends of the line.
You can use line.rstrip("\n") to remove only the trailing "\n".
+
* line.rstrip("\n") remove only the trailing "\n".
 +
 
 +
 
 +
==Hitung banyak word==
 +
 
 +
len(string.split())
  
  
Line 12: Line 17:
 
Pakai str.join:
 
Pakai str.join:
  
with open('file.txt') as f:
+
with open('file.txt') as f:
    print " ".join(line.strip() for line in f)
+
    print " ".join(line.strip() for line in f)
 +
 
 +
 
 +
==Remove specific line==
 +
 
 +
f = open("yourfile.txt","r")
 +
lines = f.readlines()
 +
f.close()
 +
 
 +
f = open("yourfile.txt","w")
 +
for line in lines:
 +
  if line!="nickname_to_delete"+"\n":
 +
    f.write(line)
 +
 
 +
f.close()

Revision as of 06:19, 30 January 2017


Strip /n

  • line.strip() - remove all types of whitespaces from both ends of the line.
  • line.rstrip("\n") remove only the trailing "\n".


Hitung banyak word

len(string.split())


Join Line

Pakai str.join:

with open('file.txt') as f:
    print " ".join(line.strip() for line in f)


Remove specific line

f = open("yourfile.txt","r")
lines = f.readlines()
f.close()
f = open("yourfile.txt","w")
for line in lines:
  if line!="nickname_to_delete"+"\n":
    f.write(line)
f.close()